This article mainly introduces the detailed explanation and cases of PHP delegation model. Interested friends can refer to it. I hope it will be helpful to everyone.
Delegation Pattern
The delegation design pattern removes decisions and complex functionality from core objects by assigning or delegating to other objects.
Application Scenario
1. Designed a cd class, which has mp3 playback mode and mp4 playback mode
2. Before the improvement, the playback mode of the cd class was used , you need to determine which playback mode to choose in the instantiated class
3. After improvement, the playback mode is passed into the playList function as a parameter, and the corresponding method to be played can be automatically found.
Code: cd class, before improvement, choosing the playback mode is a painful thing
<?php //委托模式-去除核心对象中的判决和复杂的功能性 //使用委托模式之前,调用cd类,选择cd播放模式是复杂的选择过程 class cd { protected $cdInfo = array(); public function addSong($song) { $this->cdInfo[$song] = $song; } public function playMp3($song) { return $this->cdInfo[$song] . '.mp3'; } public function playMp4($song) { return $this->cdInfo[$song] . '.mp4'; } } $oldCd = new cd; $oldCd->addSong("1"); $oldCd->addSong("2"); $oldCd->addSong("3"); $type = 'mp3'; if ($type == 'mp3') { $oldCd->playMp3(); } else { $oldCd->playMp4(); }
Code: improved cd class through delegation mode
<?php //委托模式-去除核心对象中的判决和复杂的功能性 //改进cd类 class cdDelegate { protected $cdInfo = array(); public function addSong($song) { $this->cdInfo[$song] = $song; } public function play($type, $song) { $obj = new $type; return $obj->playList($this->cdInfo, $song); } } class mp3 { public function playList($list) { return $list[$song]; } } class mp4 { public function playList($list) { return $list[$song]; } } $newCd = new cd; $newCd->addSong("1"); $newCd->addSong("2"); $newCd->addSong("3"); $type = 'mp3'; $oldCd->play('mp3', '1'); //只要传递参数就能知道需要选择何种播放模式
Related Recommended:
Delegation pattern example tutorial in php
PHP advanced object-oriented design pattern: Delegation pattern usage example
php design pattern delegation pattern
The above is the detailed content of Detailed explanation and cases of PHP delegation mode. For more information, please follow other related articles on the PHP Chinese website!