一天一个设计模式---组合模式

基本概念

组合模式是一种结构型设计模式,它允许客户端统一对待单个对象和对象的组合。组合模式通过将对象组织成树形结构,使得客户端可以一致地使用单个对象和组合对象。

主要角色:

  1. Component(组件): 定义组合中的对象接口,可以是抽象类或接口,声明了用于管理子组件的方法。
  2. Leaf(叶子): 表示组合中的叶子节点对象,实现了Component接口。叶子节点没有子节点。
  3. Composite(复合): 表示组合中的具有子节点的复合对象,实现了Component接口。复合对象可以包含叶子节点和其他复合对象,形成递归结构。

优点

  • 统一接口: 客户端通过统一的接口处理单个对象和组合对象,不需要区分它们的具体类型。
  • 灵活性: 客户端可以以相同的方式处理单个对象和组合对象,从而使得系统更加灵活。
  • 可扩展性: 可以方便地添加新的组件,无需修改客户端代码。

结构

示例代码

Component 定义了组件的接口,Leaf 表示叶子节点,Composite 表示复合节点。客户端可以通过统一的 operation 方法处理单个对象和组合对象。

JS 复制代码
// Component
class Component {
  constructor(name) {
    this.name = name;
  }

  operation() {
    throw new Error('Operation not supported');
  }
}

// Leaf
class Leaf extends Component {
  operation() {
    console.log(`Leaf ${this.name} operation`);
  }
}

// Composite
class Composite extends Component {
  constructor(name) {
    super(name);
    this.children = [];
  }

  add(child) {
    this.children.push(child);
  }

  remove(child) {
    const index = this.children.indexOf(child);
    if (index !== -1) {
      this.children.splice(index, 1);
    }
  }

  operation() {
    console.log(`Composite ${this.name} operation`);
    this.children.forEach(child => child.operation());
  }
}

// Usage
const leaf1 = new Leaf('1');
const leaf2 = new Leaf('2');

const composite = new Composite('Composite');
composite.add(leaf1);
composite.add(leaf2);

const leaf3 = new Leaf('3');
const leaf4 = new Leaf('4');

const subComposite = new Composite('SubComposite');
subComposite.add(leaf3);
subComposite.add(leaf4);

composite.add(subComposite);

composite.operation();
相关推荐
_哆啦A梦4 小时前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo3 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4963 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃3 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20103 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈3 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||4 天前
安装依赖三方exe/msi的软件设计模式
设计模式
希望_睿智4 天前
实战设计模式之访问者模式
c++·设计模式·架构
茶本无香4 天前
设计模式之十六:状态模式(State Pattern)详解 -优雅地管理对象状态,告别繁琐的条件判断
java·设计模式·状态模式
驴儿响叮当20104 天前
设计模式之备忘录模式
设计模式·备忘录模式