学习php设计模式 php实现合成模式(composite)
《:学习php设计模式 php实现合成模式(composite)》要点: PHP编程一、意图 PHP编程Composite模式的缺点:使你的设计变得更加一般化,容易增加组件也会产生一些问题,那就是很难限制组合中的组件 PHP编程 PHP编程八、平安式的合成模式PHP示例 PHP编程
<?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();
?>
PHP编程以上就是使用php实现合成模式的代码,还有一些关于合成模式的概念区分,希望对大家的学习有所帮助. 编程之家培训学院每天发布《:学习php设计模式 php实现合成模式(composite)》等实战技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培养人才。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |