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

基本概念

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

主要角色:

  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();
相关推荐
sarasuki7 小时前
MCP 为什么是一个协议而不是一个框架呢?
设计模式·agent·mcp
geovindu10 小时前
rust: Borg Pattern(续)
开发语言·后端·设计模式·rust·博格模式
染指11101 天前
140.Agent-多Agent框架-Agent执行Skills流程
数据库·人工智能·设计模式·langchain·agents
sarasuki1 天前
Agent 是怎么做错误处理的呢?
人工智能·设计模式·agent
A1Book1 天前
从 0 设计历史专题资料汇编的 AI Agent 编排架构——六轮真实任务复盘
设计模式
geovindu2 天前
rust: Simple Factory Pattern(续)
后端·设计模式·rust·简单工厂模式·创建型模式
喜欢coding的谢同学2 天前
Go语言常用设计模式基础和实践案例介绍
开发语言·设计模式·golang
sarasuki3 天前
Agent 的记忆有几种?你的名字是?
人工智能·设计模式·agent
geovindu3 天前
rust: Flyweight Pattern
开发语言·后端·设计模式·rust·享元模式·结构型模式
沫璃染墨4 天前
《Linux工程实践篇(一):认识设计模式——从日志系统看策略模式》
linux·c++·安全·设计模式·策略模式