23 design patterns (13) - Chain of Responsibility pattern

1. Definitions

A plurality of object a chance to handle the request, so as to avoid coupling relationship requested quality of sender and receiver. This is connected into a chain receiving object, and pass the request along the chain until an object handles him up.

2, UML 图

8fHV6x.png

3, composition

  • Abstract processor (Handler) : it contains the main treatment handlerRequestand care subject nextHandler, his idea is, if he can handle it themselves, otherwise referred to the object processing
  • The processor implementation class (FirstHandler) : processor implementation class, each class to achieve their definition processing logic

4, the code

First look at a negative sample code, a large number of ifAnalyzing execution logic to select:

public Response handleRequest(Request request) {
    Level level = request.getLevel();
    if (1 == level) {
    	Handler1.handleRequest(request);
    } else if (2 == level) {
    	Handler2.handleRequest(request);
    } else if (3 == level) {
    	Handler3.handleRequest(request);
		}
    throw new RuntimeException("无法处理 ......")
}

This code has the following disadvantages:

  • Code bloat: If the judgment condition is not simple 1==level, but more complex calculations, that would be very bad code readability;
  • Coupling high: If you add a new case, you need to add a new if elsestatement, changed the original code in violation of the closed - open principle.

Here is the code using the chain of responsibility pattern:

// 抽象处理类
public abstract class Handler {
		// 下一个处理器处理
    protected Handler nextHandler;

    void setNextHandler(Handler nextHandler){
        this.nextHandler = nextHandler;
    }

    final Response handleRequest(Request request){
      	// 如果自己能处理,则自己处理
        if(request.getLevel() == getHandlerLevel()){
            return this.doHandler(request);
        }
        System.out.println("本处理器:"+getHandlerLevel()+" 无法处理,开始转交 ......");
        if(null != this.nextHandler){
          // 如果不能处理,转交给下一个处理器处理
            return this.nextHandler.handleRequest(request);
        } else {
            System.out.println("无合适的处理器,处理失败 ......");
        }
        return null;
    }
		// 自己处理的任务标识
    abstract Level getHandlerLevel();
		// 实际处理逻辑,子类自己定义
    abstract Response doHandler(Request request);
}

// 任务标识,用于区分用哪个处理器处理
public enum Level {
    FIRST_LEVEL,
    SECOND_LEVEL,
    THIRD_LEVEL;
}

//请求类
public class Request {
    private Level level;
  
    public Request(Level level){
        this.level = level;
    }
  
    public Level getLevel() {
        return level;
    }
}

// 处理结果类
public class Response {
}

// 第一个处理器
public class FirstConcreteHandler extends Handler {
    @Override
    Level getHandlerLevel() {
        return Level.FIRST_LEVEL;
    }

    @Override
    Response doHandler(Request request) {
        System.out.println("本处理器:"+getHandlerLevel()+" 开始处理 .....");
        return null;
    }
}

// 第二个处理器
public class SecondConcreteHandler extends Handler {
    @Override
    Level getHandlerLevel() {
        return Level.SECOND_LEVEL;
    }

    @Override
    Response doHandler(Request request) {
        System.out.println("本处理器:"+getHandlerLevel()+" 开始处理 .....");
        return null;
    }
}

// 第三个处理器
public class ThirdConcreteHandler extends Handler {
    @Override
    Level getHandlerLevel() {
        return Level.THIRD_LEVEL;
    }

    @Override
    Response doHandler(Request request) {
        System.out.println("本处理器:"+getHandlerLevel()+" 开始处理 .....");
        return null;
    }
}

//调用者
public class Main {

    public static void main(String[] args) {
        Handler firstHandler = new FirstConcreteHandler();
        Handler secondHandler = new SecondConcreteHandler();
        Handler thirdHandler = new ThirdConcreteHandler();

        firstHandler.setNextHandler(secondHandler);
        secondHandler.setNextHandler(thirdHandler);
				// 需要第三个处理类处理
        Request request = new Request(Level.THIRD_LEVEL);
        firstHandler.handleRequest(request);
    }
}

Output:

本处理器:FIRST_LEVEL 无法处理,开始转交 ......
本处理器:SECOND_LEVEL 无法处理,开始转交 ......
本处理器:THIRD_LEVEL 开始处理 .....

5, the advantages and disadvantages

  • Only in the case of each of the code in the record chain up, the user only needs to know one inlet tube without performing specific logic;
  • Chain of Responsibility pattern is a disguised version of the if elsestatement, if the chain is too long, excessive consumption performance;
  • Chain follow the chain of responsibility case cited not appear, there would be an infinite loop

6, application scenarios

Chain of Responsibility pattern is actually a flexible version of the if…else…statement, but it put conditions on the judgment of each class node chain. If it appears the code if…else…statement causes poor readability, consider the chain of responsibility pattern.

Guess you like

Origin www.cnblogs.com/moongeek/p/12556425.html