组合模式

  • 定义:将对象组合成树形结构以表示‘部分-整体’的层次结构。
    组合模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 定义组件
abstract class IComponent {
name:string
constructor(name:string) {
this.name = name
}
add(c: IComponent) {}
remove(c: IComponent) {}
display(depth: number) {}
}
// 定义叶节点
class Leaf extends IComponent {
add() {
console.log('cannot add a leaf')
}
remove() {
console.log('cannot remove from a leaf')
}
display(d:number) {
console.log('-'.repeat(d)+this.name)
}
}
// 定义容器
class Composite extends IComponent {
children:IComponent[] = []
add(c: IComponent) {
this.children.push(c)
}
remove(c: IComponent) {
let i = this.children.indexOf(c)
this.children.splice(i, 1)
}
display(d:number) {
console.log('-'.repeat(d)+this.name)
this.children.forEach(c => c.display(d + 2))
}
}

// 使用
const root = new Composite('root')
root.add(new Leaf('leafA'))
root.add(new Leaf('leafB'))

const comp = new Composite('compX')
comp.add(new Leaf('leafXa'))

root.add(comp)

const comp2 = new Composite('compXY')

comp2.add(new Leaf('leafXYA'))

comp.add(comp2)

root.add(new Leaf('leafC'))

root.display(1)