设计模式php实例:组合模式
来源:互联网 发布:js switch case语句 编辑:程序博客网 时间:2024/06/15 10:31
组合模式有时候又叫做部分-整体模式,它把程序内部简单元素和复杂元素提供给客户端统一的接口,使客户端和程序的内部结构结构,内部可以随意更改扩展。
从类图上看组合模式形成一种树形结构,由枝干和叶子继承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();
- 设计模式php实例:组合模式
- [PHP设计模式]Composite(组合)模式范例
- PHP设计模式之组合模式
- [php] 设计模式之 组合模式
- PHP设计模式——组合模式
- PHP:设计模式之组合模式
- php 设计模式(组合模式一)
- php设计模式(组合模式2)
- PHP设计模式之组合模式
- 设计模式:组合模式
- 设计模式-----组合模式
- 设计模式 组合模式
- 设计模式--组合模式
- 设计模式---组合模式
- 【设计模式】组合模式
- 设计模式 - 组合模式
- 设计模式----组合模式
- 设计模式 - 组合模式
- CS106A Assignment4: Hangman
- Flash Stage3D 学习笔记(一)
- 【业务知识】暴雪让ARPG进入2.0时代
- Oracle的内外连接
- Android之ActionBar学习 (译)
- 设计模式php实例:组合模式
- sql2005 ip地址点分十进制与长整形表示法相互转换
- 由于没有公钥,下列签名无法进行验证: NO_PUBKEY 60D11217247D1CFF
- MyEclipse修改项目名称
- xcode4.2 完成输入后关闭键盘
- STM32 关于复位类型的判断及软件复位
- MVC数据从Controller传递到View之ViewModel
- C/C++的XML编程+libxml2的使用方法
- 服务器数据库系列 - MYSQL优化20条经验