1.裝飾器模式(Decorator),可以動態地添加修改類的功能
2.一個類提供了一項功能,如果要在修改並添加額外的功能,傳統的編程模式,需要寫一個子類繼承它,並重新實現類的方法
3.使用裝飾器模式,僅需在運行時添加一個裝飾器對象即可實現,可以實現最大的靈活性
<?php /** * 輸出一個字符串 * 裝飾器動態添加功能 * Class EchoText */ class EchoText { protected $decorator = []; public function Index() { //調用裝飾器前置操作 $this->beforeEcho(); echo "你好,我是裝飾器。"; //調用裝飾器后置操作 $this->afterEcho(); } //增加裝飾器 public function addDecorator(Decorator $decorator) { $this->decorator[] = $decorator; } //執行裝飾器前置操作 先進先出原則 protected function beforeEcho() { foreach ($this->decorator as $decorator) $decorator->before(); } //執行裝飾器后置操作 先進后出原則 protected function afterEcho() { $tmp = array_reverse($this->decorator); foreach ($tmp as $decorator) $decorator->after(); } } /** * 裝飾器接口 * Class Decorator */ interface Decorator { public function before(); public function after(); } /** * 顏色裝飾器實現 * Class ColorDecorator */ class ColorDecorator implements Decorator { protected $color; public function __construct($color) { $this->color = $color; } public function before() { echo "<dis style='color: {$this->color}'>"; } public function after() { echo "</div>"; } } /** * 字體大小裝飾器實現 * Class SizeDecorator */ class SizeDecorator implements Decorator { protected $size; public function __construct($size) { $this->size = $size; } public function before() { echo "<dis style='font-size: {$this->size}px'>"; } public function after() { echo "</div>"; } } //實例化輸出類 $echo = new EchoText(); //增加裝飾器 $echo->addDecorator(new ColorDecorator('red')); //增加裝飾器 $echo->addDecorator(new SizeDecorator('22')); //輸出 $echo->Index();