擴展一個類一般可以使用繼承或者組合的形式。使用繼承的方式擴展時,隨着基類子類的增多,以及子類的子類出現,繼而出現了代碼的無限制膨脹,增加了系統的複雜性。而使用裝飾者模式既繼承又引用,能動態擴展類的一些功能,減少了繼承數量。
裝飾紙UML類圖:
php代碼實例(出自php設計模式)
/**
* 裝飾模式
*/
/**
* 抽象構件角色
*/
interface Component {
/**
* 示例方法
*/
public function operation();
}
/**
* 裝飾角色
*/
abstract class Decorator implements Component{
protected $_component;
public function __construct(Component $component) {
$this->_component = $component;
}
public function operation() {
$this->_component->operation();
}
}
/**
* 具體裝飾類A
*/
class ConcreteDecoratorA extends Decorator {
public function __construct(Component $component) {
parent::__construct($component);
}
public function operation() {
parent::operation(); // 調用裝飾類的操作
$this->addedOperationA(); // 新增加的操作
}
/**
* 新增加的操作A,即裝飾上的功能
*/
public function addedOperationA() {
echo 'Add Operation A <br />';
}
}
/**
* 具體裝飾類B
*/
class ConcreteDecoratorB extends Decorator {
public function __construct(Component $component) {
parent::__construct($component);
}
public function operation() {
parent::operation();
$this->addedOperationB();
}
/**
* 新增加的操作B,即裝飾上的功能
*/
public function addedOperationB() {
echo 'Add Operation B <br />';
}
}
/**
* 具體構件
*/
class ConcreteComponent implements Component{
public function operation() {
echo 'Concrete Component operation <br />';
}
}
/**
* 客戶端
*/
class Client {
/**
* Main program.
*/
public static function main() {
$component = new ConcreteComponent();
$decoratorA = new ConcreteDecoratorA($component);
$decoratorB = new ConcreteDecoratorB($decoratorA);
$decoratorA->operation();
$decoratorB->operation();
}
}
Client::main();