<?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