Php design mode: decorator mode, php design mode
The modifier mode allows you to dynamically add and modify the class.
A class provides a function. to modify and add additional functions, the traditional programming mode needs to write a subclass to inherit it and re-implement the class method. You can use the decorator mode by adding a decorator object at run time to achieve maximum flexibility.
DrawDecorator.php
<? Phpnamespace Baobab;/*** Interface DrawDecorator * @ package Baobab * Interface, which defines two methods, you can add additional capabilities before and after rendering the canvas */interface DrawDecorator {function beforeDraw (); function afterDraw ();}
Canvas.php
<? Phpnamespace Baobab;
/**
* Canvas class, Drawing Graphics
**/
Class Canvas {public $ data;Protected $ decorators = array ();// Decorator function init ($ width = 20, $ height = 10) {$ data = array (); for ($ I = 0; $ I <$ height; $ I ++) {for ($ j = 0; $ j <$ width; $ j ++) {$ data [$ I] [$ j] = '*'; }}$ this-> data = $ data ;}Function addDecorator (DrawDecorator $ decorator) {$ this-> decorators [] = $ decorator;} function beforeDraw () {foreach ($ this-> decorators as $ decorator) {$ decorator-> beforeDraw () ;}} function afterDraw () {$ decorators = array_reverse ($ this-> decorators); foreach ($ decorators as $ decorator) {$ decorator-> afterDraw ();}}Function draw (){$ This-> beforeDraw ();Foreach ($ this-> data as $ line) {foreach ($ line as $ char) {echo $ char;} echo "<br/> \ n ";}$ This->AfterDraw ();} Function rect ($ a1, $ a2, $ b1, $ b2) {foreach ($ this-> data as $ k1 => $ line) {if ($ k1 <$ a1 or $ k1> $ a2) continue; foreach ($ line as $ k2 => $ char) {if ($ k2 <$ b1 or $ k2> $ b2) continue; $ this-> data [$ k1] [$ k2] = '& nbsp; ';}}}}
ColorDrawDecorator.php
<? Phpnamespace Baobab ;/**
* Decorator for modifying the image color
*/Class ColorDrawDecorator implements \ Baobab \ DrawDecorator {protected $ color; function _ construct ($ color = 'black') {$ this-> color = $ color ;} function beforeDraw () {echo "<div style = 'color: {$ this-> color}; '> ";}
Function afterDraw () {echo "</div> ";}}
SizeDrawDecorator.php
<? Phpnamespace Baobab ;/**
* Decorator for modifying the image size
*/Class SizeDrawDecorator implements \ Baobab \ DrawDecorator {protected $ size; function _ construct ($ size = '12px ') {$ this-> size = $ size ;} function beforeDraw () {echo "<div style = 'font-size: {$ this-> size}; '> ";}
Function afterDraw () {echo "</div> ";}}
Index. php
$ Canvas = new Baobab \ Canvas (); $ canvas-> init (); $ canvas-> rect (3, 6, 4, 12 ); $ canvas-> addDecorator (new \ Baobab \ ColorDrawDecorator ('blue'); $ canvas-> addDecorator (new \ Baobab \ SizeDrawDecorator ('10px '));
......
// You can add more decorators.
$ Canvas-> draw ();