http://www.runoob.com/design-pattern/composite-pattern.html
https://www.webfalse.com/read/201739/1268854.html
https://my.oschina.net/botkenni/blog/1603660
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
这种模式创建了一个包含自己对象组的类。该类提供了修改相同对象组的方式。
意图:将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
方式:树枝和叶子实现统一接口,树枝内部组合该接口。
使用场景:部分、整体场景,如树形菜单,文件、文件夹的管理。
class component{
public $name;
public $list=[];
public function __construct($name){
$this->name = $name;
}
public function add(component $component){
$this->list[$component->name] = $component;
}
public function remove(component $component){
unset($this->list[$component->name]);
}
public function getList(){
return $this->list;
}
}
$tree = new component('tree');
$leaf_0 = new component('leaf_0');
$leaf_1 = new component('leaf_1');
$tree->add($leaf_0);
$tree->add($leaf_1);
$leaf_0_0 = new component('leaf_0_0');
$leaf_0_1 = new component('leaf_0_1');
$leaf_0->add($leaf_0_0);
$leaf_0->add($leaf_0_1);
print_r($tree->getList());