JS design pattern (2) -- single case pattern

Posted by murali on Fri, 20 Dec 2019 15:33:44 +0100

Let's continue with Xiaoming's example
Last time, when it came to Xiaoming's buying back everything, the college gentleman looked at the bill: ¥ 4386
Although I think the money costs a little more, I still need to give Xiao Ming to do the purchase this time
I'll give you a bill, Xiao Ming. You have to write down the bill for every item you buy and ask the boss to sign it

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

Order.getOrder = (function() {	//Using closures ensures that an order object is maintained
    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(`Trade name: ${this.name} Price:¥${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 'Lego': super.sell(new Good('Lego', 3600));
            case 'Building blocks': super.sell(new Good('Building blocks', 288));
        }
    }
}

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

class Student {
    constructor(name) {
        this.name = name;
        this.order = Order.getOrder();
    }
    getTotal() {
        console.log(`Total purchase price:¥${this.order.total}`);
    }
}

Xiaoming is walking on the street

let xiaoming = new Student('Xiao Ming');

Xiaoming goes into the football shop and buys football and basketball

let sportShop = new SportShop();
sportShop.sell('Football');
sportShop.sell('Basketball');

Xiaoming enters the stationery store and buys Lego and building blocks

let toyShop = new ToyShop();
toyShop.sell('Lego');
toyShop.sell('Building blocks');

Xiaoming finished purchasing

xiaoming.getTotal();

Mr. Zhang gets the bill and has a look: Oh, how expensive is LEGO? Next time, I won't buy LEGO