PHP design mode decorator mode, PHP design mode
Decorator mode, you can dynamically add the ability to modify the class.
A class provides a feature that, if you want to modify and add additional functionality, the traditional programming pattern requires writing a subclass to inherit it and re-implement the method of the class. With adorner mode, you only need to add an adorner object at run time for maximum flexibility.
drawdecorator. php
Phpnamespace Baobab; /* */interface drawdecorator{ function beforedraw () ; function Afterdraw ();}
Canvas. php
Phpnamespace Baobab;
/**
*canvas class, drawing graphics
**/
classcanvas{ Public $data; protected $decorators = array(); //Decorator functionInit$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[] = c5> $decorator; } function beforedraw () { foreach($this->decorators as c12> $decorator) { $decorator, Beforedraw (); }} function afterdraw () { $decorators = array_reverse( $this, decorators); foreach($decorators as $decorator) { $decorato R--Afterdraw (); } } functionDraw () { $this-Beforedraw (); foreach($this->data as $line) { foreach($line as $char) { Echo $char; } Echo"
\ n "; } $this Afterdraw (); } functionRect$a 1,$a 2,$b 1,$b 2) { foreach($this->data as $k 1=$line) { if($k 1<$a 1Or$k 1>$a 2)Continue; foreach($line as $k 2=$char) { if($k 2<$b 1Or$k 2>$b 2)Continue; $this->data[$k 1][$k 2] = ' '; } } }}
colordrawdecorator. php
Phpnamespace Baobab; /**
* Decorator to modify the color of the graphic
*/ class Implements \baobab\drawdecorator{ protected$color; function __construct ($color = ' Black ') { $this$color ; } function Beforedraw () { echo ' $this->color}; ' > "; }
function Afterdraw () { echo ""; }}
sizedrawdecorator. php
Phpnamespace Baobab; /**
* Decorator to modify the size of the graphic
*/ class Implements \baobab\drawdecorator{ protected$size; function __construct ($size = ' 12px ') { $this$size ; } function Beforedraw () { echo ' $this->size}; ' > "; }
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 '));
......
Additional adorners can be added
$canvas->draw ();
http://www.bkjia.com/PHPjc/1105550.html www.bkjia.com true http://www.bkjia.com/PHPjc/1105550.html techarticle PHP design mode decorator mode, PHP design mode decorator mode, you can dynamically add the ability to modify the class. A class provides a feature if you want to modify and add additional features ...