Delegate mode
By assigning or delegating other objects, the delegate design pattern can remove judgments and complex functionality from the core objects.
Application Scenarios
A CD class was designed with MP3 playback mode and MP4 playback mode in the class.
Before the improvement, using the CD class playback mode, you need in the instantiated class to determine what mode of playback mode to choose
After the improvement, the playback mode as a parameter passed into the playlist function, it will automatically find the corresponding method to play.
Code: CD class, not improved before, choose Play mode is a painful thing
[PHP]
Delegate mode-removes judgments and complex functionality from core objects
Calling the CD class before using the delegate mode, choosing CD playback mode is a complex 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: Through the delegate mode, the improved CD class
[PHP] View plaincopyprint?
Delegate mode-removes judgments and complex functionality from core objects
Improved 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 to choose
Author: initphp
http://www.bkjia.com/PHPjc/478145.html www.bkjia.com true http://www.bkjia.com/PHPjc/478145.html techarticle Delegate mode enables you to remove judgments and complex functionality from core objects by assigning or delegating other objects to the delegate design pattern. Application Scenario design a CD class, the class has mp3 play ...