1. 程式人生 > >組合模式 Composite

組合模式 Composite

ech protected des end fun etc httpd arc trac

將對象組合成樹形結構以表示整體-部分的層次結構,組合模式使得用戶對單個對象和組合對象的使用具有一致性.

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);

  

組合模式 Composite