dream

一个菜鸟程序员的成长历程

0%

设计模式之组合模式--树形结构的最佳实践

设计模式之组合模式–树形结构的最佳实践

组合模式是部分组合成整体。

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

为什么要使用组合模式

最常用到组合模式的应该就是树形结构了。

比如公司-部门的结构,文件夹-文件的结构。

首先有一个共同的父类。

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

/**
* 组合模式
* 组合抽象类
* 组合的部件和整体都继承这个抽象类,组合出这个抽象类的整体
*/
abstract class Component {

protected $name;

public function __construct($name) {
$this->name = $name;
}

/**
* 增加一个Component类型的对象
*/
public abstract function add(Component $component);

/**
* 删除一个Component类型的对象
*/
public abstract function remove(Component $component);

/**
* 展示结构
*/
public abstract function show(int $depth);

}

然后实现支节点和叶子节点两个类

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
68
69
use Illuminate\Support\Arr;
/**
* 组合模式
* 组合的支节点,可以有子节点,字节的需要是Component类型
*/
class Composite extends Component {

private $arr = [];

/**
* 增加一个Component类型的对象
*/
public function add(Component $component){
$this->arr[] = $component;
}

/**
* 删除一个Component类型的对象
*/
public function remove(Component $component) {
Arr::where($this->arr, function ($value, $key) use ($component) {
if ($value == $component) {
unset($this->arr[$key]);
}
});

}

/**
* 展示结构
*/
public function show(int $depth) {
dump(str_repeat('-',$depth) . $this->name);
foreach ($this->arr as $k => $v) {
$v->show(2+$depth);
}
}

}

/**
* 组合模式
* 组合的叶子节点
* 叶子节点不能添加和移除字节点
*/
class Leaf extends Component {

/**
* 增加一个Component类型的对象
*/
public function add(Component $component){
return '';
}

/**
* 删除一个Component类型的对象
*/
public function remove(Component $component) {
return '';
}

/**
* 展示结构
*/
public function show(int $depth) {
dump(str_repeat('-',$depth) . $this->name);
}

}

客户端通过任意添加子节点的方式来完成组合。

1
2
3
4
5
6
7
8
9
10
11
12
13
14

$root = new Composite('root');
dump($root);
$a = new Composite('a');
$root->add($a);
dump($root);
$root->remove($a);
dump($root);
$root->add($a);
$ab = new Leaf('ab');
$a->add($ab);
$b = new Composite('b');
$root->add($b);
$root->show(0);

composite

代码放在了我的github上面。