Php design mode: decorator mode and php design mode. Php design mode: modifier mode. php design mode: modifier mode. you can dynamically add and modify the class function. A class provides a function, if you want to modify and add additional features, 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
Canvas.php
/**
* 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"
\ 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] = '';}}}}
ColorDrawDecorator.php
* Decorator for modifying the image color
*/Class ColorDrawDecorator implements \ Baobab \ DrawDecorator {protected $ color; function _ construct ($ color = 'black') {$ this-> color = $ color ;} function beforeDraw () {echo"";}
Function afterDraw () {echo"
";}}
SizeDrawDecorator.php
* Decorator for modifying the image size
*/Class SizeDrawDecorator implements \ Baobab \ DrawDecorator {protected $ size; function _ construct ($ size = '12px ') {$ this-> size = $ size ;} function beforeDraw () {echo"";}
Function afterDraw () {echo"
";}}
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 ();
You can dynamically add and modify the class in the ghost or php design mode. A class provides a function. if you want to modify and add additional functions...