<?php
/*
* 组合模式定义:将对象组合成树型结构以表示"部分-整体"的层次结构.组合模式使得用户对单个对象和组合对象的使用具有一致性。
*/
//抽象的组件对象
class Component{
//输出组件自身的名称
public function printStruct($preStr){}
//向组件对象中加入组件对象
public function addChild($component){}
//从组件对象中移除某个组件
public function removeChild($component){}
//返回某个索引对象的组件对象
public function getChild($component){}
}
//叶子类的实现,由于叶子类不具有组件的功能,所以不能使用一些组件的功能
class leaf extends Component{
private $name = "";
public function __construct($name){
$this->name = $name;
}
public function printStruct($preStr){
echo $preStr."-".$this->name;
}
public function addChild($component){
trigger_error("This Object don't use addChild Function!",E_USER_ERROR);
}
public function removeChild($component){
trigger_error("This Object don't use removeChild Function!",E_USER_ERROR);
}
public function getChild($component){
trigger_error("This Object don't use getChild Function!",E_USER_ERROR);
}
}
// 组合对象类,可以包含其他的组合对象或者叶子对象
class Composite extends Component{
//组件对象数组
private $componentArr;
//自身的名称
private $name;
public function __construct($name){
$this->name = $name;
}
public function addChild($component){
//延迟初始化
if($this->componentArr == null){
$this->componentArr = array();
}
array_push($this->componentArr, $component);
}
public function printStruct($preStr){
echo $preStr."-".$this->name."<br>";
if($this->componentArr != null){
$preStr+="-";
foreach ($this->componentArr as $key => $value) {
$this->componentArr[$key]->printStruct($preStr);
}
}
}
}
$root = new Composite("服装");
$c1 = new Composite("男装");
$c2 = new Composite("女装");
$leaf1 = new leaf("衬衣");
$leaf2 = new leaf("夹克");
$leaf3 = new leaf("裙子");
$leaf4 = new leaf("套装");
$root->addChild($c1);
$root->addChild($c2);
$c1->addChild($leaf1);
$c1->addChild($leaf2);
$c2->addChild($leaf3);
$c2->addChild($leaf4);
$root->printStruct("-");
?>