<?php
//推过分配或委托至其他对象,委托设计模式能够去除核心对象中的判决和复杂的功能性。
class Playlist{
private $_songs;
public function __construct(){
$this->_songs = [];
}
public function addSong($location, $title){
$song = ['location' => $location, 'title' => $title];
$this->_songs[] = $song;
}
public function getM3U(){
$m3u = "#EXTM#3U\n\n";
foreach($this->_songs as $song){
$m3u .= "#EXTM3U:-1,{$song['title']}\n";
$m3u .= "{$song['location']}\n";
}
return $m3u;
}
public function getPLS(){
$pls = "[playlist]\nNumberOfEntries=".count($this->_songs)."\n\n";
foreach ($this->_songs as $songCount => $song) {
$counter = $songCount + 1;
$pls .= "File{$counter}={$song['location']}\n";
$pls .= "Title{$counter}={$song['title']}\n";
$pls .= "Length{$counter}=-1\n\n";
}
return $pls;
}
}
$externalRetrievedType = 'pls';
$playlist = new Playlist();
$playlist->addSong('/home/aaron/music/brr.mp3', 'Brr');
$playlist->addSong('/home/aaron/music/goodbye.mp3', 'Goodbye');
if($externalRetrievedType == 'pls'){
$playlistContent = $playlist->getPLS();
}else{
$playlistContent = $playlist->getM3U();
}
echo $playlistContent;
echo PHP_EOL;
class newPlaylist{
private $_songs;
private $_typeObject;
public function __construct($type){
$this->_songs = [];
$object = "{$type}PlaylistDelegate";
$this->_typeObject = new $object;
}
public function addSong($location, $title){
$song = ['location' => $location, 'title' => $title];
$this->_songs[] = $song;
}
public function getPlaylist(){
$playlist = $this->_typeObject->getPlaylist($this->_songs);
return $playlist;
}
}
class m3uPlaylistDelegate{
public function getPlaylist($songs){
$m3u = "#EXTM#3U\n\n";
foreach($songs as $song){
$m3u .= "#EXTM3U:-1,{$song['title']}\n";
$m3u .= "{$song['location']}\n";
}
return $m3u;
}
}
class plsPlaylistDelegate{
public function getPlaylist($songs){
$pls = "[playlist]\nNumberOfEntries=".count($songs)."\n\n";
foreach ($songs as $songCount => $song) {
$counter = $songCount + 1;
$pls .= "File{$counter}={$song['location']}\n";
$pls .= "Title{$counter}={$song['title']}\n";
$pls .= "Length{$counter}=-1\n\n";
}
return $pls;
}
}
$playlist = new newPlaylist($externalRetrievedType);
$playlist->addSong('/home/aaron/music/brr.mp3', 'Brr');
$playlist->addSong('/home/aaron/music/goodbye.mp3', 'Goodbye');
$playlistContent = $playlist->getPlaylist();
echo $playlistContent;
转载于:https://blog.51cto.com/hehe1987/1831696