Appearance
装饰器设计模式 / Decorator
装饰器设计模式允许你动态地添加或修改对象的功能,并且不修改原有对象的结构。
Code
javascript
class Cup {
getCost() {
return 5;
}
}
class CupDecorator {
constructor(cup) {
this.cup = cup;
}
getCost() {
return this.cup.getCost() + 3;
}
}
const cup = new Cup();
const cupWithDecorator = new CupDecorator(cup);
cup.getCost(); // -> 5
cupWithDecorator.getCost(); // -> 8