装饰模式

/**
 * 规定装饰类与被装饰类都必须实现的方法
 */
interface component {
    function operation();
}
/**
 * 被装饰的类
 */
class concrete_component implements component {
    public function operation() {
        echo '具体履行职责的对象<br/>';
    }
}

/**
 * 装饰器抽象类
 */
abstract class decorator_component implements component {
    protected $component;
    /**
     * 添加装饰器方法
     */
    public function set_component (component $component) {
        $this->component = $component;
    }    
    public function operation() {
        if( $this->component != null ) {
            $this->component->operation();
        }
    }
}

/**
 * 第一个装饰器
 */
class decorator_a extends decorator_component{
    public function operation() {
        parent::operation();
        echo 'decorator_a<br/>';
    }
}

/**
 * 第二个装饰器
 */
class decorator_b extends decorator_component{
    public function operation() {
        parent::operation();
        echo 'decorator_b<br/>';
    }
}

$concrete_component = new concrete_component();

$decorator_a = new decorator_a();
$decorator_a->set_component($concrete_component);

$decorator_b = new decorator_b();
$decorator_b->set_component($decorator_a);
$decorator_b->operation();

装饰模式(decorator):动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

posted @ 2015-06-27 17:18  扬空  阅读(150)  评论(0编辑  收藏  举报