装饰模式
就是动态的给一个对象添加一些额外的职责。
实例:
申明一个抽象类:
<?php
abstract class Component {
public abstract function operation();
}
申明一个对象类,可以给Component
类添加职责:
<?php
class ConcreateComponent extends Component {
public function operation()
{
echo '对象的职责';
}
}
申明一个装饰器类(Decorator
):
<?
abstract class Decorator extends Component {
protected $component = null;
public function setComponent(Component $component) {
$this->component = $component;
}
public function operation()
{
if ($this->component != null) {
$this->component->operation();
}
}
}
申明两个新类,继承装饰类,添加新的职责:
<?
class DecoratorA extends Decorator {
public function operation()
{
parent::operation();
echo '新的职责1';
}
}
class DecoratorB extends Decorator {
public function operation()
{
parent::operation();
echo '新的职责2';
}
}
客户端代码:
$component = new ConcreateComponent();
$decoratorA = new DecoratorA();
$decoratorB = new DecoratorB();
$decoratorA->setComponent($component);
$decoratorB->setComponent($decoratorA);
$decoratorB->operation();
结果:
对象的职责新的职责1新的职责2
这样就达到了给类动态添加职责的效果。如果采用传统的方法,只能是在类中添加方法,但是我们后期添加的功能是针对一些特殊场合的,如果硬编码在原始类中,会增加类的复杂度。使用装饰模式
可以简化核心类的职责,又能实现给类增加功能。