JS設計模式(二)--- 單例模式

帕尼尼0_0發表於2018-10-06

我們繼續說小明那個例子
上次說到小明買回了所有的東西,書院的先生一看賬單:¥4386
雖然覺得這錢花的有點多,但這一次的採購還是要交給小明去做
先生說:小明啊,我給你一個賬單,你每買一件商品都要在這個賬單上寫上,並讓老闆簽字

class Order {
    constructor() {
        this.goodList = [];
        this.total = 0;
    }
    add(good) {
        this.goodList.push(good);
        this.total += good.price;
    }
}

Order.getOrder = (function() {	//使用閉包,保證了維護一個order物件
    let order;
    return function() {
        if(!order) {
            order = new Order();
        }
        return order;
    }
})();

class Good {
    constructor(name, price) {
        this.name = name;
        this.price = price;
    }
    showInfo() {
        console.log(`商品名:${this.name} 價格:¥${this.price}`);
    }
}

class Shop {
    constructor() {
        this.order = Order.getOrder();
    }
    sell(good) {
        this.order.add(good);
    }
}

class ToyShop extends Shop{
    constructor() {
        super();
    }
    sell(name) {
        switch(name) {
            case '樂高': super.sell(new Good('樂高', 3600));
            case '積木': super.sell(new Good('積木', 288));
        }
    }
}

class SportShop extends Shop{
    constructor() {
        super();
    }
    sell(name) {
        switch(name) {
            case '足球': super.sell(new Good('足球', 80));
            case '籃球': super.sell(new Good('籃球', 65));
        }
    }
}

class Student {
    constructor(name) {
        this.name = name;
        this.order = Order.getOrder();
    }
    getTotal() {
        console.log(`採購商品總價:¥${this.order.total}`);
    }
}

小明走在大街上…

let xiaoming = new Student('小明');

小明進了球具店,買了足球和籃球

let sportShop = new SportShop();
sportShop.sell('足球');
sportShop.sell('籃球');

小明進了文具店,買了樂高和積木

let toyShop = new ToyShop();
toyShop.sell('樂高');
toyShop.sell('積木');

小明結束了採購

xiaoming.getTotal();

先生拿到賬單(order)一看:哦,原來樂高怎麼貴啊,下次就不買樂高了哈

相關文章