JS设计模式(二)--- 单例模式

我们继续说小明那个例子
上次说到小明买回了所有的东西,书院的先生一看账单:¥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)一看:哦,原来乐高怎么贵啊,下次就不买乐高了哈

你可能感兴趣的:(JS设计模式(二)--- 单例模式)