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