Delegation Mode
The delegation design pattern removes arbitrariness and complex functionality from the core object by assigning or delegating it to other objects.
Application scenarios
Designed a cd class, which has mp3 playback mode and mp4 playback mode
Before the improvement, when using the cd class playback mode, you need to determine which playback mode to choose in the instantiated class
After the 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, selecting the playback mode was a pain
[php]
//Delegation pattern - removes decisions and complex functionality in core objects
//Before using the delegation mode, call the cd class and select the cd playback mode is a complicated selection process
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] view plaincopyprint?
//Delegation pattern - removes decisions and complex functionality in core objects
//Improve cd class
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'); //Just pass the parameters to know which playback mode needs to be selected
Author: initphp