定义
组合模式,是一种结构型设计模式,它允许你将对象组合成树形结构来表现**“整体-部分”**的层次关系。
它使得客户端对单个对象和组合对象的使用具有一致性。在组合模式中,有两个角色:叶子(Leaf) 对象和组合(Composite) 对象,它们实现相同的接口。
UML 类图
typescript 实现
1. 定义组件接口
interface Component {
execute(): void;
}
2. 创建叶子类
class Leaf implements Component {
private name: string;
constructor(name: string) {
this.name = name;
}
public execute(): void {
console.log(`Leaf ${this.name} performs execute`);
}
}
3. 创建组合类
class Composite implements Component {
private children: Component[] = [];
private name: string;
constructor(name: string) {
this.name = name;
}
public add(child: Component) {
this.children.push(child);
}
public remove(child: Component): void {
const childIndex = this.children.indexOf(child);
if(childIndex !== -1) {
this.children.splice(childIndex, 1);
}
}
public execute(): void {
console.log(`Composite ${this.name} performs execute`);
for(const child of this.children) {
child.execute();
}
}
}
4. 使用示例
// 创建叶子节点
const leaf1 = new Leaf("1");
const leaf2 = new Leaf("2");
const leaf3 = new Leaf("3");
// 创建根节点
const root = new Composite("Root");
root.add(leaf1);
// 创建一个组合节点,并添加叶子节点
const composite1 = new Composite("Composite1");
composite1.add(leaf2);
composite1.add(leaf3);
// 将组合节点添加到根组合节点
root.add(composite1);
// 执行组合结构中所有组件的操作
root.execute();
通用实现
无