CleverCode最近在看组合模式。
1 模式介绍
将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
2 模式中的角色
1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component子部件。
2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等。
3 模式结构
4 项目
4.1 部门与叶子节点
4.2 源码
<?php
/**
* php组合模式
* copyright http://blog.csdn.net/CleverCode
*
*/
abstract class Component
{/*{{{*/
protected $id;
protected $name;
public function __construct($id,$name)
{
$this->id = $id;
$this->name = $name;
}
abstract public function add(Component $c);
abstract public function remove(Component $c);
abstract public function display($depth);
}/*}}}*/
class Composite extends Component
{/*{{{*/
private $children = array();
public function add(Component $c)
{
$this->children[$c->id] = $c;
}
public function remove(Component $c)
{
unset($this->children[$c->id]);
}
public function display($depth)
{
$str = str_pad('', $depth , "_");
echo "{$str} {$this->name}\r\n";
foreach($this->children as $c)
{
$c->display($depth+2);
}
}
}/*}}}*/
class Leaf extends Component
{/*{{{*/
private $children = array();
public function add(Component $c)
{
echo "can not add to a leaf\r\n";
}
public function remove(Component $c)
{
echo "can not remove to a leaf\r\n";
}
public function display($depth)
{
$str = str_pad('', $depth , "_");
echo "{$str} {$this->name}\r\n";
}
}/*}}}*/
class Client
{/*{{{*/
public static function main($argv)
{
$root = new Composite(1,'root');
$root->add(new Leaf(2,'leaf 2'));
$root->add(new Leaf(3,'leaf 3'));
$com1 = new Composite(4,'com1');
$com1->add(new Leaf(5,'com1 leaf 1'));
$com1->add(new Leaf(6,'com1 leaf 2'));
$root->add($com1);
$root->display(1);
}
}/*}}}*/
Client::main($argv);
?>
4.3 结果展示
技术交流
CleverCode是一名架构师,技术交流,咨询问题,请加CleverCode创建的qq群(架构师俱乐部):517133582。加群和腾讯,阿里,百度,新浪等公司的架构师交流。【架构师俱乐部】宗旨:帮助你成长为架构师!