JavaScript中的装饰器模式

以下是关于 装饰器模式(Decorator Pattern) 的系统梳理,涵盖核心概念、实现方式、应用场景及注意事项,帮助我们掌握这种灵活扩展对象能力的经典设计模式:


一、装饰器模式基础

1. 核心概念
  • 定义:动态地为对象添加额外职责,相比继承更灵活,遵循 开放-封闭原则(对扩展开放,对修改封闭)。
  • 核心思想:通过包装对象(装饰器)增强功能,而非修改原始对象。
  • 参与者
    • Component(组件接口):定义被装饰对象的接口。
    • ConcreteComponent(具体组件):实现基础功能的对象。
    • Decorator(装饰器基类):继承/实现组件接口,持有组件引用。
    • ConcreteDecorator(具体装饰器):添加具体增强功能。
2. 基础实现(ES5 示例)
// 组件接口
class Coffee {
   
  cost() {
    return 5; }
}

// 装饰器基类
class CoffeeDecorator {
   
  constructor(coffee) {
   
    this.coffee = coffee;
  }
  cost() {
   
    return this.coffee.cost();
  }
}

// 具体装饰器:加牛奶
class MilkDecorator extends CoffeeDecorator {
   
  cost() {
   
    return super.cost() + 2;
  }
}

// 具体装饰器:加糖
class SugarDecorator extends CoffeeDecorator {
   
  cost() {
   
    return super.cost() + 1;
  }
}

// 使用
let coffee = new Coffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(coffee.cost()); // 8

二、JavaScript 装饰器语法(ES7+)

1. 类装饰器
function logClass(target) {
   
  console.log(`装饰类: ${
     target.name

你可能感兴趣的:(前端核心知识总结,前端,javascript,装饰器模式)