应用场景
装饰器模式,能有效地把核心职责和附加功能隔离开。比如微信机器人,就和适合用装饰器模式,把核心功能(接收信息等)和其他附件功能(比如自动回复,根据照片识别年龄)隔开。
UML图
代码实现
- component.php
<?php
//定义职责,给其他的类继承
abstract class Component
{
public abstract function operation();
}
- concreteComponent.php
<?php
require_once './Component.php';
/**
* 对应核心业务
*/
class ConcreteComponent extends Component
{
public function operation()
{
// TODO: Implement operation() method.
echo '核心业务', PHP_EOL;
}
}
- decorator.php
<?php
/**
* 抽象装饰器类,对应附加业务,用于给具体的装饰器继承
*/
abstract class Decorator extends Component
{
/**
* @var Component
*/
protected $component;
public function setComponent(Component $component)
{
$this->component = $component;
}
public function operation()
{
// TODO: Implement operation() method.
if ($this->component != null) {
$this->component->operation();
}
}
}
- ConcreteDecoratorA.php 和 ConcreteDecoratorB.php
<?php
//具体的装饰器对象
class ConcreteDecoratorA extends Decorator
{
public function operation()
{
parent::operation(); // TODO: Change the autogenerated stub
echo 'ConcreteDecoratorA 的操作' , PHP_EOL;
}
}
//具体的装饰器B
class ConcreteDecoratorB extends Decorator
{
public function operation()
{
parent::operation(); // TODO: Change the autogenerated stub
echo 'ConcreteDecoratorB 的操作' , PHP_EOL;
}
}
- 调用以上代码
<?php
require_once './Component.php';
require_once './Decorator.php';
require_once './ConcreteComponent.php';
require_once './ConcreteDecoratorA.php';
require_once './ConcreteDecoratorB.php';
//调用处
$c = new ConcreteComponent();
$d1 = new ConcreteDecoratorA();
$d2 = new ConcreteDecoratorB();
$d1->setComponent($c);
$d2->setComponent($d1);
$d2->operation();
输出结果