• PHP设计模式之装饰者模式


    <?php
    
    /*
    装饰者模式动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
    */
    header("Content-type:text/html; charset=utf-8");
    
    //使用继承进行组合
    
    abstract class MessageBoardHandler
    {
        public function __construct(){}
        abstract public function filter($msg);
    }
    
    
    class MessageBoard extends MessageBoardHandler
    {
        public function filter($msg)
        {
            return "处理留言板上的内容".$msg;
        }
    }
    
    $obj = new MessageBoard();
    echo $obj -> filter("一定要学好装饰模式<br/>");
    
    
    
    
    // --- 以下是使用装饰模式 ----
    // 定义装饰者类----
    
    // 引入被装饰殾对象---
    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 HtmlFilter extends MessageBoardDecorator
    {
        public function __construct($handler)
        {
            parent::__construct($handler);
        }
        
        public function filter($msg)
        {
            return "过滤掉HTML标签|".parent::filter($msg);
        }
    }
    
    
    class SensitiveFilter extends MessageBoardDecorator
    {
        public function __construct($handler)
        {
            parent::__construct($handler);
        }
    
        public function filter($msg)
        {
            return "过滤掉HTML|".parent::filter($msg);// 过滤掉敏感词的处理这时只是加个文字没有进行处理
        }
        
    }
    
        $obj = new HtmlFilter(new SensitiveFilter(new MessageBoard()));
        
        echo $obj->filter("一定学好装饰模式<br/>");
  • 相关阅读:
    天国近了(一) 揭穿OOP神话
    自然思考:流程任意定制的一个问题
    风水占卜是迷信吗?
    飘浮的鸡蛋壳真正的原理研究
    ListView
    Java与WCF交互(一):Java客户端调用WCF服务 (转)
    WPF ListView 数据绑定
    .NET中Trace类和Debug类的应用举例(转)
    Print Visual Tree
    EntityFramework之领域驱动设计实践(六)(转)
  • 原文地址:https://www.cnblogs.com/hubing/p/3302806.html
Copyright © 2020-2023  润新知