裝飾器模式,可以動態地添加修改類的功能。
一個類提供了一項功能,如果要修改並添加額外的功能,傳統的編程模式需要寫一個子類繼承它,並重新實現類的方法。使用裝飾器模式,僅需要在運行時添加一個裝飾器對象即可實現,可以實現最大的靈活性。
DrawDecorator.php
<?php namespace Baobab; /** * Interface DrawDecorator * @package Baobab * 裝飾器接口,定義兩個方法,渲染畫布之前和之後可添加額外的能力 */ interface DrawDecorator{ function beforeDraw(); function afterDraw(); }
Canvas.php
<?php namespace Baobab;
/**
*Canvas類,繪制圖形
**/
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] = ' '; } } } }
ColorDrawDecorator.php
<?php namespace Baobab; /**
*修改圖形顏色的裝飾器
*/ 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
<?php namespace Baobab; /**
*修改圖形大小的裝飾器
*/ 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'));
......
//可添加其他更多裝飾器
$canvas->draw();