• 设计模式之 责任链模式


    责任链模式是一种非常有趣的模式。

    责任链模式用于避免请求发送者与多个请求处理者耦合在一起,让所有请求的处理者持有下一格对象的引用,从而将请求串联成一条链,在有请求发生时,可将请求沿着这条链传递,直到遇到该对象的处理器。

    image

    (1)定义处理接口

    public interface Handler{
        void operator();
    }

    (2)定义抽象处理类

    public abstract class AbstractHandler{
        private Handler handler;
        
        public Handler getHandler() {
            return handler;
        }
        
        public void setHandler(Handler handler) {
            this.handler = handler;
        }
    }

    (3)定义责任类

    public class AuthHandler extends AbstractHandler implements Handler{
        private final static Log logger = LogFactory.getLog(this.getClass());
        private String name;
        public AuthHandler(String name){
            this.name = name;
        }
        @Override
        public void operator(){
            logger.info("user auth...");
            if (getHandler() != null){
                getHandler().operator();
            }
        }
    }
    
    public class BusinessHandler extends AbstractHandler implements Handler{
        private final static Log logger = LogFactory.getLog(this.getClass());
        private String name;
        public BusinessHandler(String name){
            this.name = name;
        }
        @Override
        public void operator(){
            logger.info("business info handler ...");
            if (getHandler() != null){
                getHandler().operator();
            }
        }
    }
    
    public class ResponseHandler extends AbstractHandler implements Handler{
        private final static Log logger = LogFactory.getLog(this.getClass());
        private String name;
        public ResponseHandler(String name){
            this.name = name;
        }
        @Override
        public void operator(){
            logger.info("response  ...");
            if (getHandler() != null){
                getHandler().operator();
            }
        }
    }

    (4)使用责任链模式

    public static void main(String[] args){
        AuthHandler authHandler = new AuthHandler("auth");
        BusinessHandler businessHandler = new BusinessHandler("business");
        ResponseHandler responseHandler = new ResponseHandler("response");
        authHandler.setHandler(businessHandler);
        businessHandler.setHandler(responseHandler);
    }

  • 相关阅读:
    可在广域网部署运行的QQ高仿版 -- GG叽叽(源码)
    区间合并
    二分查找算法模板
    神经网络详解(RNN/LSTM)
    反向传播算法推导过程(非常详细)
    机器学习-回归问题(Regression)
    从RNN到LSTM
    神经网络浅讲:从神经元到深度学习
    部署高并发python后端(Systemd+Nginx+Gunicorn+Gevent+Supervisor+Flask )
    产品笔记 | 软件版本号—规范与命名规则
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15238268.html
Copyright © 2020-2023  润新知