php 组合模式,Composite_组合模式_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."
";

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("-");

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值