Delegation Mode
By assigning or entrusting other objects, the delegated design mode can remove the judgment and complex functions of the core objects.
Application scenarios
A cd class is designed, which includes mp3 and mp4 Playback modes.
Before improvement, when using the cd-type playback mode, you need to determine the method of playing in the instantiated class.
After the improvement, the playback mode is passed into the playList function as a parameter, and the corresponding playback method is automatically found.
Code: cd class. It is a pain to select the playing mode before it is improved.
[Php]
<? Php
// Delegate mode-Remove judgment and complex functionality from core objects
// Before using the delegate mode, call the cd class. Selecting 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]. 'hangzhou ';
}
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?
<? Php
// Delegate mode-Remove judgment and complex functionality from core objects
// Improve the 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'); // you only need to pass the parameters to know which playback mode to select.
Author: initphp