Overview of the Chain of Responsibility:

Chain of responsibility is one of the behavior design patterns. In the chain of responsibility pattern, many objects are connected in a chain by each object’s reference to its next parent. Requests pass along the chain until one of the objects on the chain decides to process the request. The client making the request does not know which object on the chain ultimately handles the request, allowing the system to dynamically reorganize and assign responsibilities without affecting the client.

The roles involved in the chain of responsibility mode are as follows:

  • Abstract Handler role: Defines an interface to handle requests. If necessary, the interface can define a method to set and return a reference to the next parent. This role is typically implemented by a Java abstract class or Java interface. The Handler class aggregation in the figure above gives a reference to a specific subclass’s next parent, and the abstract method handleRequest() specifies how subclasses handle requests.
  • The ConcreteHandler role: When a ConcreteHandler receives a request, it can choose to either process it or pass it on to the next provider. Because the concrete handler holds a reference to the next home, the concrete handler can access the next home if needed.

For example:

/** * @author liuml * @explain abstract chain * @time 2018/8/6 20:37 */ public abstract class HandlerChain {protected HandlerChain mHandlerChain; // Set the responsibility chain of the next level public voidsetSuccessor(HandlerChain handlerChain){
        this.mHandlerChain = handlerChain;
    }

    public abstract void requext(int request);

}
Copy the code
Public class ConcretHandler1 extends HandlerChain {public class ConcretHandler1 extends Handler1; @Override public void requext(int request) {if (request < 10) {
            System.out.println("I'm the first rung in the chain of responsibility and I processed the request." + request);
        }else{ this.mHandlerChain.requext(request); }}}Copy the code
Public class ConcretHandler2 extends HandlerChain {public class ConcretHandler2 extends HandlerChain {public class ConcretHandler2 extends HandlerChain { @Override public void requext(int request) {if (request > 10) {
            System.out.println("I'm the second level in the chain of responsibility and I processed the request." + request);
        } else {
            System.out.println("Request" + request + "No one can handle it."); }}}Copy the code

test

Public class Main {public static void Main (String[] args) {ConcretHandler1 ConcretHandler1 = new ConcretHandler1(); ConcretHandler2 concretHandler2 = new ConcretHandler2(); / / handle client creates a connection to form chain concretHandler1. SetSuccessor (concretHandler2); // Create a task, here are some numbers of different sizes, processor processing results are different; int[] requests = {1, 10, 23, 40};for(int request : requests) { concretHandler1.requext(request); }}}Copy the code

Print the result

I'm level one in the chain of responsibility and I processed request 1 request 10 and nobody else can process it and I'm level two in the chain of responsibility and I processed request 23 and I processed request 40Copy the code

Description and examples from baidu encyclopedia and https://blog.csdn.net/disiwei1012/article/details/53557436

Practical application in Android development

Take a practical example. In Android development, what happens when users have different roles and each role has access to different modules?

For example, the value of role is 1, 2, and 3, representing three positions: stubborn bronze, bright silver, and glorious gold.

The following module can only be accessed above the silver level normally

if(role = = 2 | | role = = 3) {/ / can enter}else{// cannot enter} // orif(role>=2){//else{// do not enter} or require each permission to do something for each moduleif(role ==1 ){
   
}else if(role == 2){
    
}else{}Copy the code

Platinum, diamond, master, king (I haven’t played lol for a long time)

A module is good if the APP module slowly increases the permissions more and more, how to do, if you modify under this code it will violate the open and close principle, the code is not easy to maintain.


Using the chain of responsibility model, modify the above code

/** * @author liuml * @explain abstract chain * @time 2018/8/6 20:37 */ public abstract class HandlerChain {protected HandlerChain mHandlerChain; // Set the responsibility chain of the next level public voidsetSuccessor(HandlerChain handlerChain){ this.mHandlerChain = handlerChain; } public abstract boolean requext(int request); } public class ConcretHandler1 extends HandlerChain {int;} public class ConcretHandler1 extends HandlerChain {int role = 1; @Override public boolean requext(int request) {if (Constant.role >= request && Constant.role == role) {
            System.out.println("Unyielding brass processed the request." + request);
            return true;
        } else {
            returnthis.mHandlerChain.requext(request); }} /** * public class ConcretHandler2 extends HandlerChain {** * public class ConcretHandler2 extends HandlerChain { int role = 2; @Override public boolean requext(int request) {if (Constant.role >= request && Constant.role == role) {
            System.out.println("Bright Silver processed the request." + request);
            return true;
        } else {
            returnmHandlerChain.requext(request); Public class ConcretHandler3 extends HandlerChain {}} public class ConcretHandler3 extends HandlerChain {}} public class ConcretHandler3 extends HandlerChain { int role = 2; @Override public boolean requext(int request) {if (Constant.role >= request && Constant.role == role) {
            System.out.println("Honor Gold processed the request." + request);
            return true;
        } else {
            System.out.println("Current Permissions"+Constant.role+"Request" + request + "No one can handle it.");
            return false; Public class Constant {public static int role = 2; } /** * @author liuml * @explain * @time 2018/8/7 16:53 */ public class HandlerChainStaticFactory { public static ConcretHandler1createOne() {return new ConcretHandler1();
    }

    public static ConcretHandler2 createTwo() {return new ConcretHandler2();
    }

    public static ConcretHandler3 createThree() {returnnew ConcretHandler3(); }} /** * @author liuml * @explain static inner class singleton * @time 2018/8/7 16:55 */ public class HandlerChainUtil {private static ConcretHandler1 mConcretHandler1 = null; private final ConcretHandler2 mConcretHandler2; private final ConcretHandler3 mConcretHandler3; publicHandlerChainUtil() {/ / create the processor mConcretHandler1 = HandlerChainStaticFactory createOne (); mConcretHandler2 = new ConcretHandler2(); mConcretHandler3 = new ConcretHandler3(); / / handle client creates a connection to form chain mConcretHandler1. SetSuccessor (mConcretHandler2); mConcretHandler2.setSuccessor(mConcretHandler3); } public static HandlerChainUtilgetInstance() {return HandlerChainUtilHolder.sHandlerChainUtil;
    }

    public  static boolean request(int request){
       return mConcretHandler1.requext(request);
    }

    public static class HandlerChainUtilHolder{
        public  static final HandlerChainUtil sHandlerChainUtil = new HandlerChainUtil();
    }
}


public class Main {

    public static void main(String[] args) {


        System.out.println("Test for permissions:"+HandlerChainUtil.getInstance().request(2)+"\n");
        System.out.println("Test for permissions:"+HandlerChainUtil.getInstance().request(1)+"\n");
        System.out.println("Test for permissions:"+HandlerChainUtil.getInstance().request(3)+"\n");
        System.out.println("Test for permissions:"+HandlerChainUtil.getInstance().request(4)+"\n"); }}Copy the code

Last print:

Brightsilver processed request 2 to test whether it has permissions:trueBrightsilver processed request 1 to test whether it has permissions:trueCurrent permission 2, request 3 no one can handle test whether there is permission:falseCurrent permission 2, request 4 No one can handle test whether there is permission:false
Copy the code

Applicable scenarios of responsibility chain mode

As in the example above, if… The else… Statements that are unable to organize a chain of responsibility can be used to refactor code that looks bad.

In addition:

== Ordered broadcasting can also implement the chain of responsibility mode ==

Use of the open source framework OKHTTP responsibility chain pattern

https://blog.csdn.net/qq_15274383/article/details/78485648