设计模式之组合模式–树形结构的最佳实践
组合模式
是部分组合成整体。
将对象组合成树形结构以表示’部分’-‘整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
为什么要使用组合模式
最常用到组合模式的应该就是树形结构了。
比如公司-部门的结构,文件夹-文件的结构。
首先有一个共同的父类。
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; }
public abstract function add(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;
class Composite extends Component {
private $arr = [];
public function add(Component $component){ $this->arr[] = $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 {
public function add(Component $component){ return ''; }
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);
|

代码放在了我的github上面。