装饰器模式

参考 CBF4FILE <<您的设计模式  我们的设计模式>>

第一副图显示一个最简单的装饰想法:只有一个装饰类,一个原始类。通过对原始类的一次装饰直接输出。

第二副图显示了一种能够扩展的装饰模式图:原始类只是一个虚拟类,可以派生出多个实际需要装饰的类。并且装饰类也可以是多种多样的。

<?php
abstract class Component {
    abstract public function Operation();
}

class ConcreteComponent extends Component {
    public function Operation() {
        echo 'primal function<br/>';   
    }
}

abstract class Decorator extends Component {
    protected $_component;

    public function __construct($component) {
        $this->_component = $component;
    }
}

class ConcreteDecoratorA extends Decorator {
    protected $_state;

    public function __construct($component, $state) {
        parent::__construct($component);
        $this->_state = $state;
    }

    public function Operation() {
        echo $this->_state.' ';
        $this->_component->Operation();   
    }
}

class ConcreteDecoratorB extends Decorator {
    private function AddedBehavior() {
        echo 'function decorate ';   
    }

    public function Operation() {
        $this->AddedBehavior();
        $this->_component->Operation();
    }
}

$component = new ConcreteDecoratorA(new ConcreteComponent(), 'attribute decorate');
$component->Operation();

$component = new ConcreteDecoratorB(new ConcreteComponent());
$component->Operation();
?>

原文地址:https://www.cnblogs.com/jesseZh/p/3051090.html