设计原则:类应该对扩展开放,对修改关闭。
装饰者模式动态地将责任附加到对象上。 若要扩展功能,装饰者提供了比继承更有弹性 的替代方案。
class Milk {
constructor(goods) {
this.goods = goods;
}
cost() {
return this.goods.cost() + 2;
}
getDescription() {
return this.goods.getDescription() + ",milk";
}
}
class Mocha {
constructor(goods) {
this.goods = goods;
}
cost() {
return this.goods.cost() + 1.5;
}
getDescription() {
return this.goods.getDescription() + ",mocha";
}
}
class Coffee {
constructor(description) {
this.description = description;
}
getDescription() {
return this.description;
}
}
class Espresso extends Coffee {
constructor() {
super("Espresso");
}
cost() {
return 5;
}
}
class HouseBlend extends Coffee {
constructor() {
super("HouseBlend");
}
cost() {
return 4;
}
}
let coffee = new Mocha(new Milk(new HouseBlend()));
console.log(coffee.getDescription()); //HouseBlend,milk,mocha
console.log(coffee.cost()); //7.5