zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    React native 之 图标库ECharts的使用
    使用jquery给html标签加点击事件
    React native 之 async/await
    CSS布局之flexbox
    Swiper 的引入
    给浏览器设置一张背景图,并且拉动浏览器大小时图片不要被压缩变形
    境界的彼方_lduoj_bfs宽搜
    2021美国大学生数学建模大赛==ABCDEF+思路解析==
    3045 Lcm与Gcd构造
    对拍程序
  • 原文地址:https://www.cnblogs.com/happig/p/5389228.html
Copyright © 2011-2022 走看看