JS设计模式(一)--- 工厂模式

故事的开头是这样子的…
在很久很久以前,有一个学生叫小明
有一天,老师对小明,小明啊,你去给班上买一个篮球,一个足球,一套积木和一套乐高

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

class Shop {
    constructor(customer) {
        this.customer = customer;
    }
    sell(good) {
        this.customer.buy(good);
        this.customer.total += good.price;
    }
}

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

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

class Student {
    constructor(name) {
        this.name = name;
        this.goodList = [];
        this.total = 0;
    }
    buy(good) {
        this.goodList.push(good);
    }
    getTotal() {
       console.log(`${this.name}一共花费了¥${this.total}`);
    }
}

于是,小明拿着钱,走在大街上…

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

小明进了球具店,买了足球和篮球

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

小明进了文具店,买了乐高和积木

let toyShop = new ToyShop(xiaoming);
toyShop.sell('乐高');
toyShop.sell('积木');

小明结束了采购

xiaoming.getTotal();

小明并不关心每次购买的过程是怎样的:商家库存少了一个商品,商家盈利了多少钱,小明账单上多了多少钱
小明只关注一件事情:商家卖出了一件商品给我

你可能感兴趣的:(JS设计模式(一)--- 工厂模式)