美文网首页PHP经验分享
设计模式(二):装饰器模式(Decorator)

设计模式(二):装饰器模式(Decorator)

作者: 小马别过河 | 来源:发表于2019-12-02 00:54 被阅读0次
应用场景

装饰器模式,能有效地把核心职责和附加功能隔离开。比如微信机器人,就和适合用装饰器模式,把核心功能(接收信息等)和其他附件功能(比如自动回复,根据照片识别年龄)隔开。

UML图
装饰器模式.png
代码实现
  1. component.php
<?php

//定义职责,给其他的类继承
abstract class Component
{
    public abstract function operation();
}
  1. concreteComponent.php
<?php
require_once './Component.php';

/**
 * 对应核心业务
 */
class ConcreteComponent extends Component
{
    public function operation()
    {
        // TODO: Implement operation() method.
        echo '核心业务', PHP_EOL;
    }
}
  1. 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();
        }
    }
}
  1. 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;
    }
}
  1. 调用以上代码
<?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();

输出结果


输出

相关文章

网友评论

    本文标题:设计模式(二):装饰器模式(Decorator)

    本文链接:https://www.haomeiwen.com/subject/nlxtgctx.html