PHP实现组合模式

【特点】
将对象组合成树形结构以表示”部分-整体”的层次结构。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();
?>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值