使用委托模式目的是消除潜在的、难以控制的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();
时间: 2024-10-19 07:57:00