组合模式是一种结构型设计模式,它允许客户端统一对待单个对象和对象的组合。组合模式通过将对象组织成树形结构,使得客户端可以一致地使用单个对象和组合对象。
主要角色:
Component 定义了组件的接口,Leaf 表示叶子节点,Composite 表示复合节点。客户端可以通过统一的 operation 方法处理单个对象和组合对象。
// 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();