关于php:php设计模式八装饰器模式

52次阅读

共计 1250 个字符,预计需要花费 4 分钟才能阅读完成。

装璜器模式

  1. 动静的增加批改类性能
  2. 一个类提供了一项性能,如果要在批改并增加额定的性能,传统计划须要写一个子类继承,并从新实现类办法
  3. 应用装璜器模式,仅须要在运行时减少一个装璜器对象
// 例如批改 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();

正文完
 0