PHP设计模式之组合模式定义与应用示例
程序员文章站
2022-06-15 14:39:32
本文实例讲述了php设计模式之组合模式定义与应用。分享给大家供大家参考,具体如下:
本文实例讲述了php设计模式之组合模式定义与应用。分享给大家供大家参考,具体如下:
<?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 . " --------- \r\n "; 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 . " \r\n "; } } 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(); } } // 实例一下 // 人 $item3 = new item("baidu", "www.baidu.com"); $item4 = new item("google", "www.google.com"); $item1 = new item("163", "www.163.com"); $item2 = new item("sina", "www.sina.com"); // 班级 $submenu1 = new menu("sub menu1"); $submenu1->add($item1); $submenu1->add($item2); $submenu2 = new menu("sub menu2"); $submenu2->add($item3); $submenu2->add($item4); $submenu3 = new menu("sub menu3"); $submenu3->add($item3); $submenu3->add($item4); // 所有班级 $allmenu = new menu("all menu"); $allmenu->add($submenu1); $allmenu->add($submenu2); $allmenu->add($submenu3); // 打印所有班级 $objclient = new client($allmenu); $objclient->displaymenu(); // 打印第2 班级 $objclient->setmenu($submenu2); $objclient->displaymenu(); ?>
运行结果:
-- all menu ---------
-- sub menu1 ---------
163#www.163.com
sina#www.sina.com
-- sub menu2 ---------
baidu#www.baidu.com
google#www.google.com
-- sub menu3 ---------
baidu#www.baidu.com
google#www.google.com
-- sub menu2 ---------
baidu#www.baidu.com
google#www.google.com