组合模式实现方式一
2017-02-22 15:49
190 查看
<?php // 组合模式 function echoLine($msg) { echo $smg, '<br/>'; } interface Component { public function doAction(); } /** * 局部类 */ class Leaf implements Component { public function doAction() { echoLine('The [leaf] doAction!'); } } /** * 组合模式的一个问题是如何实现 add 和 remove 方法。一般的组合模式会在抽象超类中添加 add * 和 remove 方法。这可以确保模式中的所有类都共享同一个借口,但这同时也意味着局部类也必须 * 实现这些方法。实际上,我们并不希望在局部类中实现这些方法。 * * 需要担心的问题: * 1. 组合操作的成本。 * 2. 对象持久化问题。难以直接将数据保存在关系型数据中,但其数据却非常适合持久化为 XML。 */ class Composite implements Component { /** * component container */ private $container = array(); public function doAction() { echoLine('The [Composite] doAction!'); foreach ($this->container as $c) $c->doAction(); } /** * add component * @param Component $c */ public function addComponent(Component $c) { if(!in_array($c, $this->container, true)) $this->container[] = $c; } /** * remove conponent * @param Component $c */ public function removeComponent(Component $c) { $this->container = array_diff($this->container, array($c)); } /** * get all components * @return array */ public function getComponents() { return $this->container; } } // test code $leaf = new Leaf(); $composite = new Composite(); $composite->addComponent($leaf); $composite->addComponent(new Leaf()); $composite->addComponent(new Leaf()); $composite->doAction();
相关文章推荐
- 外观模式-facade实现interface的方式(简单工厂+facade组合使用)
- 组合模式实现方式二
- 用模板实现单例模式(线程安全)、模板方式实现动态创建对象
- PHP面向对象设计模式-8.1继承和组合对比-代码实现
- 我所理解的设计模式(C++实现)——组合模式(Composite Pattern)
- 设计模式C++实现(7)——外观模式、组合模式
- JAVA中的饿汉式和饱汉式单例模式及jdk中Runtime类的单例模式实现方式详解
- OpenJweb平台中自定义组合查询条件窗口的实现方式(经典之作)
- 单例模式的两种实现方式及区别
- java设计模式学习笔记5 适配器模式几种实现方式
- 我所理解的设计模式(C++实现)——组合模式(Composite Pattern)
- 【java】单例模式的两种实现方式
- 设计模式之组合模式java实现
- Java中四种线程安全的单例模式实现方式
- 从零开始学C++之模板(四):用模板实现单例模式(线程安全)、模板方式实现动态创建对象
- Java设计模式(二):单例模式的5种实现方式,以及在多线程环境下5种创建单例模式的效率
- 桥接模式的很好实现方式(应用shared_ptr)
- Ext.get() 和 Ext.query() 组合使用 实现 最灵活的取元素方式
- 设计模式:单例模式(Singleton) java实现及实现方式对比
- 最常用的设计模式---组合模式(C++实现)