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

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

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

    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);
    }

  • 相关阅读:
    01Python基础_02变量
    01Python基础_04输入输出方式
    01Python基础_03运算符
    Spring Cloud 入门教程 搭建配置中心服务
    Spring Cloud入门教程Hystrix断路器实现容错和降级
    Spring Boot 2.0.1 入门教程
    Spring Cloud入门教程Ribbon实现客户端负载均衡
    Spring Cloud 入门教程 Eureka服务注册与发现
    代理模式
    最短路径算法——Dijkstra and Floyd算法
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15238268.html
Copyright © 2011-2022 走看看