装饰模式可以在不适用创造更多子类的情况下,给对象增加额外的职责,使对象的功能得以扩展
抽象构件(Component)角色:定义一个对象接口,以规范准本接收附加职责的对象,从而可以给这些对象动态地添加职责
具体构件(Concrete Component)角色:定义一个将要接收附件职责的类
装饰(Decorator)角色:持有一个指向Component对象的指针,并定义一个与Component接口一致的接口
具体装饰(Concrete Decorator)角色:负责给构件增加附加的职责
/**
*Decorator 装饰模式
*/
/**
*抽象构件角色
*/
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();//新增加的操作
}
/**
*新增加的操作A,即装饰上的功能
*/
public function addedOperationB()
{
echo 'Add Operation B<br/>';
}
}
/**
*具体构件
*/
class ConcreteComponent implements Component
{
public function operation()
{
echo 'Concrete Component operation<br/>';
}
}
class Client
{
public static function main()
{
$component = new ConcreteComponent();
$decoratorA = new ConcreteDecoratorA($component);
$decoratorB = new ConcreteDecoratorB($decoratorA);
$decoratorA->operation();
echo '-------------------<br/>';
$decoratorB->operation();
}
}
Client::main();
程序输出:
每使用一个具象化的装饰类,原有的对象就增加该装饰类的装饰功能。