设计模式php实例:装饰者模式

扩展一个类一般可以使用继承或者组合的形式。使用继承的方式扩展时,随着基类子类的增多,以及子类的子类出现,继而出现了代码的无限制膨胀,增加了系统的复杂性。而使用装饰者模式既继承又引用,能动态扩展类的一些功能,减少了继承数量。


装饰纸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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章