zoukankan      html  css  js  c++  java
  • 责任链模式

      实现责任链模式有4个要素,处理器抽象类、处理器实现类、保存处理器的信息、处理执行

      常见责任链的实现方式有两种,一种是数组轮询:例如过滤器filter的实现,一种是链表传递:例如netty实现

      两种形式伪代码实现

     

      下面给出一个链式调用的demo

    package com.example.test;
    
    
    /**
     * 链表形式调用,维护链和链的触发
     */
    public class PipelineDemo {
    
        //链表头部,什么也不做,用作链表的触发执行
        private HandlerChainContext head = new HandlerChainContext((handerChainContext,obj) ->{
            handerChainContext.runNext(obj);
        });
    
        public void addLast(AbstractHandler handler){
            HandlerChainContext handlerChainContext = head;
            while (handlerChainContext.next!=null){
                handlerChainContext = handlerChainContext.next;
            }
            handlerChainContext.next = new HandlerChainContext(handler);
    
        }
    
    
        public void process(Object obj){
            this.head.handler(obj);
        }
    
        public static void main(String[] args) {
            PipelineDemo pipelineDemo = new PipelineDemo();
            pipelineDemo.addLast(new Hander1());
            pipelineDemo.addLast(new Hander2());
            pipelineDemo.addLast(new Hander2());
            pipelineDemo.addLast(new Hander1());
            pipelineDemo.process("开始了,");
        }
    
    
    
    }
    
    /**
     * 抽象接口
     */
    interface AbstractHandler{
    
        void handler(HandlerChainContext handlerChainContext,Object obj);
    
    }
    
    /**
     * 具体实现
     */
    class Hander1 implements AbstractHandler{
        @Override
        public void handler(HandlerChainContext handlerChainContext, Object obj) {
            obj = obj.toString() + "hand1处理完毕~~~";
            System.out.println(obj);
            handlerChainContext.runNext(obj);
        }
    }
    
    
    class Hander2 implements AbstractHandler{
        @Override
        public void handler(HandlerChainContext handlerChainContext, Object obj) {
            obj = obj.toString() + "hand2处理完毕~~~";
            System.out.println(obj);
            handlerChainContext.runNext(obj);
        }
    }
    
    /**
     * 链表上下文 存储链信息
     */
    class HandlerChainContext{
    
        HandlerChainContext next;
    
        private AbstractHandler handler;
    
        public HandlerChainContext(AbstractHandler handler){
            this.handler = handler;
        }
    
        public void handler(Object obj){
            this.handler.handler(this,obj);
        }
    
        void runNext(Object obj){
            if(this.next!=null){
                this.next.handler(obj);
            }
        }
    
    
    }
  • 相关阅读:
    nginx端口重定向及反向代理
    Linux Crontab实现定时备份和删除Docker中的Mysql数据库
    Linux创建定时任务
    Docker可视化管理工具Portainer的安装配置及使用
    Centos磁盘扩容-免重启
    使用CSS让网页自适配手机端
    Centos7 安装FTP
    Centos7 部署的Redis无法远程访问
    移动端调试
    select2初始化默认选中值(多选)
  • 原文地址:https://www.cnblogs.com/hhhshct/p/10585927.html
Copyright © 2011-2022 走看看