在传统的面向对象的语言中,给对象添加功能常常使用继承的方式,但是继承方式并不灵活,还会带来许多问题:
一方面会导致超类和子类之间存在强耦合性,当超类改变时,子类也会随之改变;另一方面,继承这种功能通常被称为"白箱复用",在
class Beverage {
constructor(description = "Unknown beverage") {
this.description = description;
}
getDescription() {
return this.description;
}
cost() {
throw new Error("This method must be overwritten!");
}
}
class CondimentDecorator extends Beverage {}
class Espresso extends Beverage {
cost() {
return 1.99;
}
}
class HouseBlend extends Beverage {
cost() {
return 0.89;
}
}
class Mocha extends CondimentDecorator {
constructor(beverage) {
super();
this.beverage = beverage;
}
getDescription() {
return this.beverage.getDescription() + ", Mocha";
}
cost() {
return 0.2 + this.beverage.cost();
}
}
class Whip extends CondimentDecorator {
constructor(beverage) {
super();
this.beverage = beverage;
}
getDescription() {
return this.beverage.getDescription() + ", Whip";
}
cost() {
return 0.6 + this.beverage.cost();
}
}
let oEspressoWithMochaAndWhip = new Espresso();
oEspressoWithMochaAndWhip = new Mocha(oEspressoWithMochaAndWhip);
oEspressoWithMochaAndWhip = new Whip(oEspressoWithMochaAndWhip);
console.log(oEspressoWithMochaAndWhip.cost());