The delegate mode of PHP design mode

Source: Internet
Author: User

The delegate mode of PHP design mode

The purpose of using the delegate mode is to eliminate potentially difficult-to-control if/else statements.

<?PHP/** * Original program notation * @var Playlist*/$playlist=Newplaylist ();$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 ();}

The above is just an example, if there are more types, then there will be more than one if/else and each additional type needs to modify the original file, the original class. The next delegation model will change the status quo. The class of the delegate pattern does not provide the actual solution, and the accepted parameters are given to different classes to solve the actual problem.

/** * Class for Delegate mode*/classnewplaylist{Private $__songs; Private $__typeobject;  Public function__construct ($type)    {        $this->__songs =Array(); $object= "{$type}playlist "; $this->__typeobject =New $object; }     Public functionAddsong ($location,$title)    {        $song=Array(' Location ' =$location, ' title ' = =$title); $this->__songs[] =$song; }     Public functiongetplaylist () {$playlist=$this->__typeobject->getplaylist ($this-__songs); return $playlist; }}

/** * M3U Delegate*/classm3uplaylistdelegate{ Public functionGetplaylist ($songs)    {        $m 3u= "#EXTM3U \ n"; }    /*Other function*/}/** * pls Delegate*/classplsplaylistdelegare{functionGetplaylist ($songs)    {        $pls=" "; }}

Each additional type only needs to add a corresponding class, and pay attention to the wording to unify, the specific use of the method will not exist if/else judgment. Examples are shown below.

/** *$extType = ' pls '; // $extTyle = ' m3u '; $playlist new newplaylist ($extType); $playlistContent $playlist->getplaylist ();

The delegate mode of PHP design mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.