设计模式 组合模式

image

介绍

组合模式是一种结构型设计模式,它允许将对象组合成树形结构,并且能够像对待单个对象一样对待整个组合对象。

角色

角色 说明
Composite 组合对象
Leaf 叶子对象

角色示例

在这个示例中,抽象组件类 Component 定义了组件的基本方法,包括 add()remove()display() 方法。叶子组件类 Leaf 继承自 Component 类,但是它不能添加或删除子组件,因为它没有子组件。容器组件类 Composite 继承自 Component 类,可以添加和删除子组件,并且可以显示自己的名称以及子组件的名称。我们通过创建一个组件树来演示组合模式的使用,然后通过调用根组件的 display() 方法来显示整个组件树。

代码

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
<?php
// 抽象组件类
abstract class Component {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function add(Component $component);
abstract public function remove(Component $component);
abstract public function display();
}
// 叶子组件类
class Leaf extends Component {
public function add(Component $component) {
echo "不能添加叶子节点\n";
}
public function remove(Component $component) {
echo "不能删除叶子节点\n";
}
public function display() {
echo $this->name . "\n";
}
}
// 容器组件类
class Composite extends Component {
private $children = array();
public function add(Component $component) {
$this->children[] = $component;
}
public function remove(Component $component) {
foreach ($this->children as $key => $child) {
if ($child == $component) {
unset($this->children[$key]);
}
}
}
public function display() {
echo $this->name . "\n";
foreach ($this->children as $child) {
echo "--";
$child->display();
}
}
}
// 创建组件树
$root = new Composite('root');
$leaf1 = new Leaf('leaf1');
$leaf2 = new Leaf('leaf2');
$composite1 = new Composite('composite1');
$composite2 = new Composite('composite2');
$leaf3 = new Leaf('leaf3');
$root->add($leaf1);
$root->add($composite1);
$root->add($composite2);
$composite1->add($leaf2);
$composite2->add($leaf3);
// 显示组件树
$root->display();

创建 Component.php,内容如上。

执行

1
2
3
4
5
6
7
$ php Component.php
root
--leaf1
--composite1
----leaf2
--composite2
----leaf3
-------------本文结束感谢您的阅读-------------
0%