您的位置:首页 > 编程语言 > PHP开发

设计模式php实例:组合模式

2012-08-06 17:10 489 查看
组合模式有时候又叫做部分-整体模式,它把程序内部简单元素和复杂元素提供给客户端统一的接口,使客户端和程序的内部结构结构,内部可以随意更改扩展。

从类图上看组合模式形成一种树形结构,由枝干和叶子继承Compont显然不符合里氏代换原则。

组合模式类图:






php代码实例(来自http://www.linuxso.com/architecture/32350.html):

abstract class MenuComponent
{
    public $name;
    public abstract function getName();
    public abstract function add(MenuComponent $menu);

    public abstract function remove(MenuComponent $menu);

    public abstract function getChild($i);

    public abstract function show();
}

class MenuItem extends MenuComponent
{
    public function __construct($name)
    {
        $this->name = $name;
    }
    public function getName(){
        return $this->name;
    }
    public function add(MenuComponent $menu){
        return false;
    }
    public function remove(MenuComponent $menu){
        return false;
    }

    public function getChild($i){
        return null;
    }
    public function show(){
        echo " |-".$this->getName()."\n";
    }
}

class Menu extends MenuComponent
{
    public $menuComponents = array();
    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function add(MenuComponent $menu)
    {
       $this->menuComponents[] = $menu;
    }

    public function remove(MenuComponent $menu)
    {
        $key = array_search($menu, $this->menuComponents);
        if($key !== false) unset($this->menuComponents[$key]);
    }

    public function getChild($i)
    {
        if(isset($this->menuComponents[$i])) return $this->menuComponents[$i];
        return null;
    }

    public function show()
    {
        echo ":" . $this->getName() . "\n";
        foreach($this->menuComponents as $v){
            $v->show();
        }
    }
}

class testDriver
{
    public function run()
    {
        $menu1 = new Menu('文学');
        $menuitem1 = new MenuItem('绘画');
        $menuitem2 = new MenuItem('书法');
        $menuitem3 = new MenuItem('小说');
        $menuitem4 = new MenuItem('雕刻');
        $menu1->add($menuitem1);
        $menu1->add($menuitem2);
        $menu1->add($menuitem3);
        $menu1->add($menuitem4);
        $menu1->show();
    }
}

$test = new testDriver();
$test->run();


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: