推荐答案
// www.javascriptcn.com code example
// 基础组件
class Coffee {
cost() {
return 5;
}
}
// 装饰器基类
class CoffeeDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost();
}
}
// 具体装饰器
class MilkDecorator extends CoffeeDecorator {
cost() {
return this.coffee.cost() + 2;
}
}
class SugarDecorator extends CoffeeDecorator {
cost() {
return this.coffee.cost() + 1;
}
}
// 使用示例
let coffee = new Coffee();
console.log(coffee.cost()); // 输出: 5
coffee = new MilkDecorator(coffee);
console.log(coffee.cost()); // 输出: 7
coffee = new SugarDecorator(coffee);
console.log(coffee.cost()); // 输出: 8本题详细解读
装饰器模式概述
装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许你通过将对象放入包含行为的特殊封装对象中来为原对象增加新的行为。装饰器模式的核心思想是动态地给对象添加额外的职责,而不改变其结构。
代码结构解析
基础组件 (
Coffee):Coffee类是一个基础组件,它定义了最基本的cost方法,返回咖啡的基础价格。
装饰器基类 (
CoffeeDecorator):CoffeeDecorator是一个抽象类,它持有一个Coffee对象的引用,并通过cost方法调用基础组件的cost方法。
具体装饰器 (
MilkDecorator和SugarDecorator):MilkDecorator和SugarDecorator是具体的装饰器类,它们继承自CoffeeDecorator,并在cost方法中添加了额外的价格。
使用示例
- 首先创建一个
Coffee对象,调用cost方法输出基础价格。 - 然后使用
MilkDecorator装饰Coffee对象,再次调用cost方法,输出增加了牛奶价格后的总价格。 - 最后使用
SugarDecorator装饰已经包含牛奶的Coffee对象,调用cost方法,输出增加了糖价格后的总价格。
优点
- 灵活性: 可以在运行时动态地添加或移除功能。
- 扩展性: 可以通过添加新的装饰器来扩展功能,而不需要修改现有代码。
- 单一职责原则: 每个装饰器只负责一个特定的功能,符合单一职责原则。
适用场景
- 当你需要在不修改对象结构的情况下,动态地给对象添加功能时。
- 当你需要扩展一个类的功能,但又不想通过继承来实现时。
通过装饰器模式,你可以轻松地为对象添加新的行为,而不会影响到其他对象。