设计模式-装饰
作者:edwin
日期:2019-09-15 20:18:55
所属分类:后端

动态的灵活的选择性的功能这种模式附加额外的职责到一个对象为扩展功能而动态的提供一个灵活的选择性的子类

ConcreteDecoratorB(具体装饰B)
This class adds responsibilities to the component.
(这类为组件添加责任。)

ConcreteDecoratorA(具体装饰A)
This class adds responsibilities to the component.
(这类为组件添加责任。)

Decorate(装饰)
This class maintains a reference to a Component object and defines an interface that conforms(符合) to Component's interface.
(这类维护一个组件对象的引用和定义了一个符合组件的接口的接口。)

ConcreteComponent(具体组件)
This class defines an object to which additional responsibilites can be attached.
(这个类定义了一个对象,以其可以附加额外的职责。)

Component(组件)
This class defines the interface for objects that can have responsibilities added to them dynamically.
(这个类定义了对象集的接口,可以为他们动态地添加责任。)

代码实现

<?php

// 过滤html
class HtmlFilter extends MessageBoardDecorator
{
    public function __construct($handler)
    {
        parent::__construct($handler);
    }

    public function filter($msg)
    {
        return "过滤掉HTML标签|" . parent::filter($msg);
        ; // 过滤掉HTML标签的处理 这时只是加个文字 没有进行处理
    }
}



// 过滤敏感词
class SensitiveFilter extends MessageBoardDecorator
{
    public function __construct($handler)
    {
        parent::__construct($handler);
    }

    public function filter($msg)
    {
        return "过滤掉敏感词|" . parent::filter($msg); // 过滤掉敏感词的处理 这时只是加个文字 没有进行处理
    }
}

class MessageBoardDecorator extends MessageBoardHandler
{
    private $_handler = null;

    public function __construct($handler)
    {
        parent::__construct();
        $this->_handler = $handler;
    }

    public function filter($msg)
    {
        return $this->_handler->filter($msg);
    }
}

class MessageBoard extends MessageBoardHandler
{
    public function filter($msg)
    {
        return "处理留言板上的内容|" . $msg;
    }
}

abstract class MessageBoardHandler
{
    public function __construct()
    {
    }
    abstract public function filter($msg);
}

$obj = new HtmlFilter(new SensitiveFilter(new MessageBoard()));
echo $obj->filter("装饰模式!");

评论

全部评论 / 0