您的位置:首页 > 编程语言 > PHP开发

PHP实现组合模式

2014-11-13 15:59 411 查看
【特点】

将对象组合成树形结构以表示”部分-整体”的层次结构。Composite使用户对单个对象和组合对象的使用具有一致性。

【合成模式的优点和缺点】

Composite模式的优点

1、简化客户代码

2、使得更容易增加新类型的组件

Composite模式的缺点:使你的设计变得更加一般化,容易增加组件也会产生一些问题,那就是很难限制组合中的组件

【合成模式适用场景】

1、你想表示对象的部分-整体层次结构

2、你希望用户忽略组合对象和单个对象的不同,用户将统一地使用组合结构中的所有对象。

<?php
/**
* 抽象组件角色
*/
interface Component {

/**
* 返回自己的实例
*/
public function getComposite();

/**
* 示例方法
*/
public function operation();
}

/**
* 树枝组件角色
*/
class Composite implements Component {
private $_composites;

public function __construct() {
$this->_composites = array();
}

public function getComposite() {
return $this;
}

/**
* 示例方法,调用各个子对象的operation方法
*/
public function operation() {
echo 'Composite operation begin:<br />';
foreach ($this->_composites as $composite) {
$composite->operation();
}
echo 'Composite operation end:<br /><br />';
}

/**
* 聚集管理方法 添加一个子对象
* @param Component $component  子对象
*/
public function add(Component $component) {
$this->_composites[] = $component;
}

/**
* 聚集管理方法 删除一个子对象
* @param Component $component  子对象
* @return boolean  删除是否成功
*/
public function remove(Component $component) {
foreach ($this->_composites as $key => $row) {
if ($component == $row) {
unset($this->_composites[$key]);
return TRUE;
}
}

return FALSE;
}

/**
* 聚集管理方法 返回所有的子对象
*/
public function getChild() {
return $this->_composites;
}

}

class Leaf implements Component {
private $_name;

public function __construct($name) {
$this->_name = $name;
}

public function operation() {
echo 'Leaf operation ', $this->_name, '<br />';
}

public function getComposite() {
return null;
}
}

/**
* 客户端
*/
class Client {

/**
* Main program.
*/
public static function main() {
$leaf1 = new Leaf('first');
$leaf2 = new Leaf('second');

$composite = new Composite();
$composite->add($leaf1);
$composite->add($leaf2);
$composite->operation();

$composite->remove($leaf2);
$composite->operation();
}

}

Client::main();
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息