美文网首页
拦截过滤器模式

拦截过滤器模式

作者: 散装咖啡 | 来源:发表于2017-05-30 02:57 被阅读36次
    //interceptingFilter
    interface Filter
    {
        public function execute($request);
    }
    
    class AuthenticationFilter implements Filter
    {
        public function execute($request)
        {
            echo "Authenticating request: " . $request;
        }
    }
    
    class DebugFilter implements Filter
    {
        public function execute($request)
        {
            echo "request log: " . $request;
        }
    }
    
    class Target
    {
        public function execute($request)
        {
            echo "Executing request: " . $request;
        }
    }
    
    class FilterChain
    {
        private $filters = [];
        private $target = null;
        
        public function __construct()
        {
            
        }
        
        public function addFilter($filter)
        {
            $this->filters[] = $filter;
        }
        
        public function execute($request)
        {
            foreach ($this->filters as $filter) {
                $filter->execute($request);
            }
            $this->target->execute($request);
        }
        
        public function setTarget($target)
        {
            $this->target = $target;
        }
    }
    
    class FilterManager
    {
        public $filterChain = null;
        
        public function __construct($filter)
        {
            $this->filterChain = new FilterChain();
            $this->filterChain->setTarget($filter);
        }
        
        public function setFilter($filter)
        {
            $this->filterChain->addFilter($filter);
        }
        
        public function filterRequest($request)
        {
            $this->filterChain->execute($request);
        }
    }
    
    class Client
    {
        public $filterManager = null;
        
        public function setFilterManager($filterManager)
        {
            $this->filterManager = $filterManager;
        }
        
        public function sendRequest($request)
        {
            $this->filterManager->filterRequest($request);
        }
    }
    
    $FilterManager = new FilterManager(new Target());
    $FilterManager->setFilter(new AuthenticationFilter());
    $FilterManager->setFilter(new DebugFilter());
    
    $Client = new Client();
    $Client->setFilterManager($FilterManager);
    $Client->sendRequest("HOME");
    

    参考文章 http://www.runoob.com/design-pattern/intercepting-filter-pattern.html

    相关文章

      网友评论

          本文标题:拦截过滤器模式

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