将对象组合成树状层次结构以表示部分-整体的层次结构,使用户对单个对象和组合对象的使用具有一致性。

两个关键词,树状,部分-整体。

举个🌰:

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
66
67
interface Component
{
public function render();
}

class Composite implements Component
{

protected array $composites = [];

public function add(Component $component)
{
$this->composites[] = $component;
}

public function remove(Component $component)
{
$position = 0;
foreach ($this->composites as $composite) {
if ($composite === $component) {
array_splice($this->composites, $position, 1);
}
$position++;
}
}

public function getChildren(int $key): Component
{
return $this->composites[$key];
}

public function render()
{
foreach ($this->composites as $composite) {
$composite->render();
}
}
}

class LeafA implements Component
{

public function render()
{
echo 'leaf a render', PHP_EOL;
}
}

class LeafB implements Component
{
public function render()
{
echo 'leaf b render', PHP_EOL;
}
}

$leafA = new LeafA();
$leafB = new LeafB();
$composite = new Composite();
$composite->add($leafA);
$composite->add($leafB);
$composite->render();

$composite->remove($leafA);
$composite->render();

$composite->getChildren(0)->render();

比较适用于树形菜单、文件和文件夹管理等,感觉场景很有限啊……