装饰者模式

装饰者模式可以在不改变对象接口的情况下动态地为对象添加额外的功能

这种模式通过将对象包装在装饰者对象中来实现,装饰者对象与原始对象实现相同的接口,但可以在运行时添加、修改或删除功能。装饰者模式提供了一种灵活的方式来扩展对象的行为,同时保持对象原有的结构和功能不变。

// 定义基础咖啡类
class SimpleCoffee {
  cost = 0;

  description = "";

  constructor() {
    this.cost = 10; // 基础咖啡价格
    this.description = "基础咖啡"; // 基础咖啡描述
  }

  getCost() {
    return this.cost;
  }

  getDescription() {
    return this.description;
  }
}

class MilkDecorator extends SimpleCoffee {
  constructor() {
    // super() 用于调用父类的构造函数。这样做的目的是在子类的实例化过程中执行父类的构造逻辑,以确保子类实例能够正确地初始化父类定义的属性。
    super();
    this.cost = this.cost + 5; // 加牛奶的价格
    this.description = this.description + ", 牛奶"; // 加牛奶的描述
  }
}

// 使用装饰者模式
let coffee1 = new SimpleCoffee();
console.log(coffee1.getDescription()); // 输出 "基础咖啡"
console.log(coffee1.getCost()); // 输出 10

let coffee2 = new MilkDecorator();
console.log(coffee2.getDescription()); // 输出 "基础咖啡, 牛奶"
console.log(coffee2.getCost()); // 输出 15

// 再次运行,原有信息不变
console.log(coffee1.getDescription()); // 输出 "基础咖啡"
console.log(coffee1.getCost()); // 输出 10
上次更新 2026/6/23 11:49:15
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8