欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php设计模式 Composite (组合模式)

程序员文章站 2022-05-31 09:29:26
复制代码 代码如下:
复制代码 代码如下:

<?php 
/** 
* 组合模式 

* 将对象组合成树形结构以表示"部分-整体"的层次结构,使得客户对单个对象和复合对象的使用具有一致性 
*/ 
abstract class menucomponent 

public function add($component){}
public function remove($component){}
public function getname(){}
public function geturl(){}
public function display(){}
}
class menu extends menucomponent
{
private $_items = array();
private $_name = null;
public function __construct($name)
{
$this->_name = $name;
}
public function add($component)
{
$this->_items[] = $component;
}
public function remove($component)
{
$key = array_search($component,$this->_items);
if($key !== false) unset($this->_items[$key]);
}
public function display()
{
echo "-- ".$this->_name." ---------<br/>";
foreach($this->_items as $item)
{
$item->display();
}
}
}
class item extends menucomponent
{
private $_name = null;
private $_url = null;
public function __construct($name,$url)
{
$this->_name = $name;
$this->_url = $url;
}
public function display()
{
echo $this->_name."#".$this->_url."<br/>";
}
}
class client
{
private $_menu = null;
public function __construct($menu)
{
$this->_menu = $menu;
}
public function setmenu($menu)
{
$this->_menu = $menu;
}
public function displaymenu()
{
$this->_menu->display();
}
}
// 实例一下
// 创建menu
$submenu1 = new menu("sub menu1");
$submenu2 = new menu("sub menu2");
$submenu3 = new menu("sub menu3");
$item1 = new item("163","www.163.com");
$item2 = new item("sina","www.sina.com");
$submenu1->add($item1);
$submenu1->add($item2);
$item3 = new item("baidu","www.baidu.com");
$item4 = new item("google","www.google.com");
$submenu2->add($item3);
$submenu2->add($item4);
$allmenu = new menu("all menu");
$allmenu->add($submenu1);
$allmenu->add($submenu2);
$allmenu->add($submenu3);
$objclient = new client($allmenu);
$objclient->displaymenu();
$objclient->setmenu($submenu2);
$objclient->displaymenu();