设计模式(六) 组合模式

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值