PHP设计模式之组合模式

  • 组合(Composite)模式 : 将一组对象组合为可像单个对象一样被使用的结构;
  • 装饰(Decorator)模式 : 通过在运行时合并对象来扩展功能的一种灵活机制;
  • 外观(Facade)模式 : 为复杂多变的系统创建一个简单的接口。
组合模式
  • 组合模式:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
  • 组合模式也许是将继承用于组合对象的最极端的例子;
    组合模式可以很好地聚合和管理许多相似的对象,因而对客户端代码来说,一个独立对象和一个对象集合是没有差别的;
  • 需求中是体现部分与整体层次的结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑用组合模式
    这里写图片描述
<?php
abstract class Component
{
    protected $name;
    public function __construct($name)
    {
        $this->name = $name;
    }

    abstract function Add(Component $c);
    abstract function Remove(Component $c);
    abstract function Display($depth);
}
// Leaf在组合中表示叶节点对象,叶节点没有子节点
class Leaf extends Component
{
    function __construct($name)
    {
        parent::__construct($name);
    }
    // 由于叶子没有再增加分枝和树叶,所以Add和Remove方法实现它没有意义,但这样做可以消除叶节点和枝节点对象在抽象层次的区别,它们具有完全一致的接口
    function Add(Component $c)
    {
        print "Cannot add to a leaf";
    }

    function Remove(Component $c)
    {
        print "Cannot remove from a leaf";
    }

    function Display($depth)
    {
        print str_repeat('-',$depth) . "{$this->name}<br />";
    }
}
// Composite定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作,比如Add和Remove
Class Composite extends Component
{
    // 一个子对象集合用来存储其下属的枝节点和叶节点
    private $children = [];
    function __construct($name)
    {
        parent::__construct($name);
    }

    function Add(Component $c)
    {
        $this->children[] = $c;
    }

    function Remove(Component $c)
    {
        foreach ($this->children as $key => $child) {
            if ($c === $child){
                unset($this->children[$key]);
            }
        }
    }

    function Display($depth)
    {
        print str_repeat('-',$depth) . "{$this->name}<br />";
        foreach ($this->children as $child) {
            $child->Display($depth+2);
        }
    }
}

$root = new Composite("root");
$root->Add(new Leaf("Leaf A"));
$root->Add(new Leaf("Leaf B"));

$comp = new Composite("Composite X");
$comp->Add(new Leaf("Leaf XA"));
$comp->Add(new Leaf("Leaf XB"));

$root->Add($comp);

$comp2 = new Composite("Composite XY");
$comp2->Add(new Leaf('leaf XYA'));
$comp2->Add(new Leaf('leaf XYB'));

$comp->Add($comp2);

$root->Add(new Leaf("Leaf C"));

$leaf = new Leaf("Leaf D");
$root->Add($leaf);
$root->Remove($leaf);

$root->Display(1);

运行结果 :
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值