php设计模式之委托模式

php设计模式之委托模式

使用委托模式目的是消除潜在的、难以控制的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

";
    }

    /*
    other function
     */
}
/**
* pls    Delegate
*/
class plsPlaylistDelegare
{
    
    function getPlaylist($songs)
    {
        $pls=" ";
    }
}

每增加一种类型只需要增加一个对应的类即可,并且注意写法要统一,具体使用方法中将不存在if/else的判断。示例如下。

/**
 * 如何使用
 */
$extType = 'pls';//$extTyle = 'm3u';
$playlist = new newPlaylist($extType);
$playlistContent = $playlist->getPlaylist();
原文地址:https://www.cnblogs.com/happig/p/5389228.html