<?php /** * @author v.r And * * @example * 委托者模式 * 经过分配或委托至其余对象,委托设计模式可以去除核心对象中的判断和复杂的功能性 * 列子: * 以音频,下载(插件安装等) * @copyright copyright information * */ class PlayList { public $songs; public function __construct() { # code... $this->songs = array(); } public function addSong($path,$title) { # code... $song = array('path' =>$path, 'title'=>$title); $this->songs = $song; } public function getM3U() { $m3u = "#EXITM3U \n\n"; foreach ($this->songs as $song) { $m3u .= "EXITMINF:-1,{$song['title']} \n"; $m3u .= "{$song['path']}"; # code... } return $m3u; # code... } public function getPLS($value='') { # code... $pls ="[playlist]\nNumberofEntries=".count($this->songs)."\n\n"; foreach ($this->songs as $key=>$song) { #.... # code... } return $pls; } } $extType = 'pls'; $playlist = new PlayList(); $playlist->addSong('/xxx/df/sdd/test.mp3','the word'); $playlist->addSong('/xxx/df/sdd/test1.mp3','Ghost Trow'); $playlistContent = ($extType == 'pls')?$playlist->getPLS() :$playlist->getM3U(); //问题? 目前软件功能只支持2种格式下载,可是市面有5种以上的格式,如今应该怎么变呢? //使用委托者进行处理 class NewPlayList { private $songs; private $typeObj; public function __construct($type) { # code... $this->songs = array(); $object = "{$type}PlayList"; $this->typeObj = new $object; } public function addSong($path,$title) { # code... $song = array('path' =>$path, 'title'=>$title); $this->songs = $song; } public function getPlayList() { # code... $palyList = $this->typeObj->getPlayList($this->songs); return $playlist; } } class m3uPlayList { public function getPlayList() { $m3u = "#EXITM3U \n\n"; foreach ($this->songs as $song) { $m3u .= "EXITMINF:-1,{$song['title']} \n"; $m3u .= "{$song['path']}"; # code... } return $m3u; # code... } } class plsPlayList { public function getPlayList() { # code... $pls ="[playlist]\nNumberofEntries=".count($this->songs)."\n\n"; foreach ($this->songs as $key=>$song) { #.... # code... } return $pls; } } class mp4PlayList { public function getPlayList() { # code... $mp4 ="[MP4/\SD/]"; return $mp4; } } $extType = 'pls'; $playList = new NewPlayList($extType); $playlistContent = $playlist->getPlayList(); #end script