组合模式能让客户以一致的方式处理个别对象以及组合对象。组合模式让客户端像修改配置文件一样简单的完成递归的动作,免除了客户端的逻辑思考。将对象组合成树状结构以表示‘部分-整体’的层次结构。
php案例:
导航目录的添加与删除:
header("content-type:text/html; charset=utf-8");
abstract class component {
abstract function addnode(component $obj);
abstract function removenode(component $obj);
abstract function show($str);
}
class branch extends component {
public $name='';
public $childnode = array();
public function __construct($name)
{
$this->name = $name;
}
public function addnode(component $obj) {
// $this->childnode[] = $obj;
array_push($this->childnode,$obj);
}
public function removenode(component $obj) {
$key = array_search($obj, $this->childnode);
unset($this->childnode[$key]);
}
public function show($str="") {
echo $this->name."<br>";
$str.=" |- ";
foreach ($this->childnode as $val) {
echo $str;
$val->show($str);
}
}
}
class leaf extends component {
public $name;
public function __construct($name) {
$this->name = $name;
}
function addnode(component $obj) {
return false;
}
function removenode(component $obj) {
return false;
}
function show($str="") {
echo $this->name."<br>";
}
}
$branch1 = new branch("家电类");
$leaf11 = new leaf("电饭煲");
$leaf12 = new leaf("电冰箱");
$leaf13 = new leaf("洗衣机");
$branch1->addnode($leaf11);
$branch1->addnode($leaf12);
$branch1->addnode($leaf13);
$branch2 = new branch("电脑类");
$branch21 = new branch("台式机");
$branch22 = new branch("笔记本");
$leaf221 = new leaf("华硕");
$leaf222 = new leaf("联想");
$leaf223 = new leaf("华为");
$leaf224 = new leaf("华夏");
$branch22->addnode($leaf221);
$branch22->addnode($leaf222);
$branch22->addnode($leaf223);
$branch22->addnode($leaf224);
$branch2->addnode($branch21);
$branch2->addnode($branch22);
$branch1->addnode($branch2);
$branch1->show();
相关推荐:
相关推荐:
常见的php设计模式分享
php设计模式之服务定位器模式实例详解
详解php设计模式之建造者模式
php设计模式之观察者模式详解
php教程:php设计模式之前言
以上就是php设计模式之组合模式与案例分享的详细内容。