设计模式之装饰器模式

134 阅读1分钟

装饰器模式: 不改变其原有的结构和功能,为对象添加新功能 比继承更加灵活

class Duck {
    constructor(name) {
        this.name = name;
    }
    eat(food) {
        console.log(this.name, '吃', food);
    }
}

class tangDuck {
    constructor(name) {
        this.duck = new Duck(name)
    }
    eat(food) {
        this.duck.eat(food)
        console.log('xieixe');
    }
}

let tang = new tangDuck('tang');
let duck = new Duck('tang');

tang.eat('苹果');
duck.eat('苹果');

实例: 买咖啡场景

class Coffee {
    make(water) {
        return `${water}+咖啡`;
    }
    cost() {
        return 10;
    }
}

class MilkCoffee {
    constructor(parent) {
        this.parent = parent;
    }
    make(water) {
        return `${this.parent.make(water)}+奶`;
    }
    cost() {
        return this.parent.cost() + 2;
    }
}
class SugarCoffee {
    constructor(parent) {
        this.parent = parent;
    }
    make(water) {
        return `${this.parent.make(water)}+糖`
    }
    cost() {
        return this.parent.cost() + 3;
    }
}

let coffee = new Coffee();
let milkCoffee = new MilkCoffee(coffee);
let sugarCoffee = new SugarCoffee(milkCoffee);

console.log(milkCoffee.cost())
console.log(sugarCoffee.cost())