白筱汐

想都是问题,做都是答案

0%

JavaScript设计模式——组合模式

介绍

组合模式,又叫做整体-部分模式,它允许你将对象组合成树形结构来表现整体-部分层次结构,让使用者可以以一致的方式处理组合对象以及部分对象。

组合模式定义的包含组合对象和叶对象的层次结构,叶对象可以被组合成更复杂的组合对象,而这个组合对象又可以被组合,这样不对的组合下去。

js 代码

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
58
59
60
61
62
63
64
65
// 抽象组件
class Component {
add(component) {}

remove(component) {}

getChild(i) {}

operation() {}
}

// 叶子组件,代表没有子节点的节点
class Leaf extends Component {
constructor(name) {
super();
this.name = name;
}

operation() {
console.log(`Leaf ${this.name} 被调用`);
}
}

// 复合组件,代表有子节点的节点
class Composite extends Component {
constructor(name) {
super();
this.name = name;
this.children = [];
}

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

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

getChild(i) {
return this.children[i];
}

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

// 使用组合模式构建对象树
const root = new Composite('root');
const leaf1 = new Leaf('leaf1');
const leaf2 = new Leaf('leaf2');
const composite = new Composite('composite');
composite.add(new Leaf('leaf3'));
composite.add(new Leaf('leaf4'));
root.add(leaf1);
root.add(leaf2);
root.add(composite);

// 调用对象树中的方法
root.operation();