装饰器模式
- 动态的添加修改类功能
- 一个类提供了一项功能,如果要在修改并添加额外的功能,传统方案需要写一个子类继承,并重新实现类方法
- 使用装饰器模式,仅需要在运行时增加一个装饰器对象
// 例如修改Canvas的draw方法
class Canvas {
private $data;
private $decorators; // 用于保存所有装饰器
public function init($hei,$wid){
for($i=0;$i<$hei;$i++){
for($i=0;$i<$wid;$i++){
$data[$i][$j] = "*";
}
}
$this->data = $data;
}
public function rect($a1,$a2,$b1,$b2) {
foreach($this->data as $k1->$line){
if($k1<$a1 or $k1 > $a2) continue;
foreach($line as $k2 => $item){
if($k2<$b2 or $k2> $b2) contine;
$this->data[$k1][$2] = ' ';
}
}
}
public function draw(){
foreach ($this->data as
$line){
foreach ($lien as $item) {
echo $item;
}
echo PHP_EOL:
}
}
// 用于增加装饰器
public function addDecorator(Decorator $decorator){
$this->decorators[] = $decorator;
}
// 前置执行
public function before(){
foreach($this->decorators as $decorator) {
$decorator->before();
}
}
public function after(){
$decorators = array_reserse($this->decorator);
foreach($decorators as $decorator) {
$decorator->before();
}
}
}
// 装饰器接口 在某个方法之前,之后加入额外操作
interface Decorator {
public function beforDraw();
public function afterDraw();
}
class ColorDecorator implements Decorator {
private $color;
public function __construct($color){
$this->color = $color;
}
public function before(){
echo 'before'.$this->color;
}
public function after(){
echo 'after';
}
}
$c = new Canvas();
$c->addDecorator(new ColorDecorator('red')); // 增加不同的装饰器,进行不同的修改
$c->rect(1,6,2,12);
$c->draw();
网友评论