Adorner mode:
If some of the content or functionality of an existing object changes, but you do not need to modify the structure of the original object or use inheritance to dynamically extend the functionality of an object, you should use adorner mode.
Simply put: We should not modify the existing class, but by creating another adorner class, through which the adorner class dynamically expands the content it needs to modify, the benefit is ————
1, we can ensure that the level of the class will not be too much confusion.
2, when we need to modify the very hour, do not change the original data structure.
The code is referenced from PHP design mode.
1 /**2 * Modified class3 today's needs:4 requires the ability to dynamically add audio tracks to a CD and to display a list of CD tracks. 5 The display should take a single line and prefix each track with a good track. 6 */7 classCD8 {9 Public $trackList;Ten function__construct () One { A #code ... - $this->tracklist=Array(); - } the - Public functionAddtrack ($track){ - $this->tracklist[]=$track; - } + - Public functiongettracklist () { + $output=" "; A foreach($this->tracklist as $key=$value) { at #code ... - $output.=($key+1). ") {$value}. "; - } - return $output; - } - } in - /* to now the demand has changed: + The audio tracks that are required to output the current instance are capitalized. - This requirement is not a particularly large requirement, and you do not need to modify the base class or create a subclass of a parent-child relationship, and then create an adorner class based on the adorner pattern. the */ * classcdtracklistdecoratorcaps{ $ Private $_CD;Panax Notoginseng - Public function__construct (CD$CD){ the $this->_cd=$CD; + } A the Public functionmakecaps () { + foreach($this->_cd->tracklist as $key=$value) { - #code ... $ $this->_cd->tracklist[$key]=Strtoupper($value);//Convert to uppercase $ } - } - } the - Wuyi //Client Testing: the $myCD=NewCD (); - Wu $trackList=Array( -"What It Means", About"Brr", $"GoodBye" - ); - foreach($trackList as $key=$value) { - #code ... A $myCD->addtrack ($value); + } the $myCDCaps=NewCdtracklistdecoratorcaps ($myCD); - $myCDCaps-makecaps (); $ Print"The CD contains the following tracks:".$myCD->gettracklist ();
The decorator mode of PHP design mode