php设计模式之委托模式
2016-04-14 21:54
836 查看
php设计模式之委托模式
使用委托模式目的是消除潜在的、难以控制的if/else语句。
上述仅仅是一个示例,如果有更多的Type,那么这里的if/else将会有多个并且每次增加类型需要增加方法。而接下来的委托模式将改变这个现状。委托模式的类在需求改变时候需要修改。
每增加一种类型只需要增加一个对应的类即可,并且注意写法要统一,具体使用方法中将不存在if/else的判断。示例如下。
使用委托模式目的是消除潜在的、难以控制的if/else语句。
<?php /** * 原来的程序写法 * @var playlist */ $playlist = new playlist(); $playlist->addSong('/home/aaron/music/aa.mp3', 'Brr'); $playlist->addSong('/home/aaron/music/bb.mp3', 'GoodBye'); if ($extType == 'pls') { $playlistContent = $playlist->getPLS(); } else { $playlistContent = $playlist->getM3U(); }
上述仅仅是一个示例,如果有更多的Type,那么这里的if/else将会有多个并且每次增加类型需要增加方法。而接下来的委托模式将改变这个现状。委托模式的类在需求改变时候需要修改。
/** * 委托模式的类 */ class newPlaylist { private $__songs; private $__typeObject; public function __construct($type) { $this->__songs = array(); $object = "{$type}Playlist"; $this->__typeObject = new $object; } public function addSong($location, $title) { $song = array('location' => $location, 'title'=>$title); $this->__songs[] = $song; } public function getPlaylist() { $playlist = $this->__typeObject->getPlaylist($this->__songs); return $playlist; } }
/** * m3u Delegate */ class m3uPlaylistDelegate { public function getPlaylist($songs) { $m3u = "#EXTM3U\n\n"; } /* other function */ } /** * pls Delegate */ class plsPlaylistDelegare { function getPlaylist($songs) { $pls=" "; } }
每增加一种类型只需要增加一个对应的类即可,并且注意写法要统一,具体使用方法中将不存在if/else的判断。示例如下。
/** * 如何使用 */ $extType = 'pls';//$extTyle = 'm3u'; $playlist = new newPlaylist($extType); $playlistContent = $playlist->getPlaylist();
相关文章推荐
- PHP练习题(一)
- [php-src]一个Php扩展的结构
- php 的快速学习和掌握。
- 在 IIS 上创建 FTP 站点
- TPLINK无线路由器怎么设置_怎么查连到当前路由器的设备的MAC地址
- 关于ajax传值。php直接post接收输出
- 面向对象的基本概念
- PHP中定义常量的几种方式与区别
- PHP里10个鲜为人知但却非常有用的函数
- SSH与FTP之间的关系与区别
- PHP正则表达式
- PHP题目
- Mediaproxy 与 Rtpproxy
- leetcode5.LongestPalindromicSubstring
- 编译安装apache+php(加常见问题解决)
- ftp 递归下载文件 下载过了就不在下载了
- PHP的UTF-8中文转拼音处理类(性能已优化至极致)
- FragmentPagerAdapter+ViewPager+Fragment
- php编译安装error: Don't know how to define struct flock on this system, set --enable-opcache=no
- yii 输入验证