组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。引用场景如树形结构,父子的操作具有一致性。
类图如下:
典型的组合模式对象结构图:
php实现:
<?php
abstract class Component{
function __construct($strName){
$this->m_strName = $strName;
}
abstract function Add($com);
protected function Remove($com){}
abstract function Display($nDepth);
}
class Leaf extends Component{
function Add($com){
print_r("Leaf can't add!");
}
function Display($nDepth){
$strtemp = "";
for($i=0;$i<$nDepth;$i++){
$strtemp.="-";
}
$strtemp=$strtemp.($this->m_strName)."\n";
print_r($strtemp);
}
}
class Composite extends Component{
protected $m_strName="";
protected $c=array();
function __construct($strName){
$this->m_strName = $strName;
}
function Add($com){
$this->c[] = $com;
}
function Remove($com){
$key = array_search($com, $this->c);
if($key != false)unset($this->c[$key]);
}
function Display($nDepth){
$strtemp = "";
for($i=0;$i<$nDepth;$i++){
$strtemp.="-";
}
$strtemp=$strtemp.($this->m_strName)."\n";
print_r($strtemp);
foreach($this->c as $v){
$v->Display($nDepth+2);
}
}
}
$p = new Composite("第一级目录");
$p->Add(new Leaf("第二级目录1"));
$s1 = new Leaf("第二级目录2");
$p->Add($s1);
$s2 = new Composite("第二级目录3");
$s2->Add(new Leaf("第三级目录1"));
$t1 = new Composite("第三级目录2");
$t1->Add(new Leaf("第四级目录"));
$s2->Add($t1);
$p->Add($s2);
$p->Remove($s1);
$p->Display(1);
执行结果如下:
-第一级目录
---第二级目录1
---第二级目录3
-----第三级目录1
-----第三级目录2
-------第四级目录