S6:组合模式 Composite

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

UML:

示例代码:
透明组合:叶节点和子节点具有相同的接口

abstract class Component
{
    protected $name;

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

    abstract public function add(Component $node);
    abstract public function remove(Component $node);
    abstract public function display($deep);
}

// 页节点
class Leaf extends Component
{
    public function add(Component $node)
    {
        // 叶不能添加节点
    }

    public function remove(Component $node)
    {
        // 叶不能删除节点
    }

    public function display($deep)
    {
        echo str_repeat('-', $deep) . $this->name . PHP_EOL;
    }

}

// 枝节点
class Composite extends Component
{
    protected $nodes = array();

    public function add(Component $node)
    {
        $this->nodes[] = $node;
    }

    public function remove(Component $node)
    {
        unset($this->nodes[array_search($node, $this->nodes)]);
    }

    public function display($deep)
    {
        echo str_repeat('-', $deep) . $this->name . PHP_EOL;

        foreach ($this->nodes as $node)
        {
            $node->display($deep + 2);
        }
    }

}


$root = new Composite('/root');
$root->add(new Leaf('/a.txt'));
$root->add(new Leaf('/b.txt'));

$etc = new Composite('/etc');
$etc->add(new Leaf('httpd'));
$etc->add(new Leaf('nginx'));

$root->add($etc);
$root->display(2);

  

示例代码:
安全组合:接口中不强制实现增加和删除节点,叶节点不具备该两项功能.

abstract class Component
{
    protected $name;

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

    abstract public function display($deep);
}

// 页节点
class Leaf extends Component
{
    public function display($deep)
    {
        echo str_repeat('-', $deep) . $this->name . PHP_EOL;
    }

}

// 枝节点
class Composite extends Component
{
    protected $nodes = array();

    public function add(Component $node)
    {
        $this->nodes[] = $node;
    }

    public function remove(Component $node)
    {
        unset($this->nodes[array_search($node, $this->nodes)]);
    }

    public function display($deep)
    {
        echo str_repeat('-', $deep) . $this->name . PHP_EOL;

        foreach ($this->nodes as $node)
        {
            $node->display($deep + 2);
        }
    }

}


$root = new Composite('/root');
$root->add(new Leaf('/a.txt'));
$root->add(new Leaf('/b.txt'));

$etc = new Composite('/etc');
$etc->add(new Leaf('httpd'));
$etc->add(new Leaf('nginx'));

$root->add($etc);
$root->display(2);

  

转载于:https://www.cnblogs.com/itfenqing/p/7788130.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值