Q: What are design patterns

Slowly: Design pattern is a solution for common scenarios in system service design, which can solve common problems encountered in the development of functional logic. Design pattern is not limited to the final implementation scheme, but in this conceptual pattern, to solve the code logic problems in system design.

Q: What is the chain of responsibility model?

Slowly: The core of the responsibility chain is to solve the sequential execution relationship in a group of services, for example, business trip loans need approval, less than 5000 yuan directly to the department leader, more than 5000 yuan need to find a higher level of leadership approval.

Q: Get on the code!

Slowly: Ok, let’s take the example above.

/ / leadership class
public abstract class Leader {
    public static int LEVE_ONE = 1;  // Level 1 leadership logo
    public static int LEVE_TWO = 2;  // Level 2 leadership logo
  
    protected int level;
    protected Leader nextLeader;
  
    public void setNextLeader(Leader nextLeader) {
        this.nextLeader = nextLeader;   // Set the subordinate's small leader
    }
  
    public void examine(a) {
        / / approval
        Leader leader = this;
        while(leader ! =null) {
            System.out.println(leader.level + "It has been approved.");
            leader = leader.nextLeader;  // Submit to the next level for approval}}}Copy the code

Level of leadership

public class OneLeader extends Leader {
    public int level = Leader.LEVEL_ONE;
  
    public OneLeader(Leader nextLeader) {
        super.setNextLeader(nextLeader); }}Copy the code

Level 2 leadership

public class TwoLeader extends Leader {
    public int level = Leader.LEVEL_TWO;
}
Copy the code

Testing:

public class Demo {
    public static void main(String[] args) {
        // Set the chain of responsibility for the leader
        TwoLeader leader2 = new TwoLeader();
        OneLeader leader1 = new OneLeader(leader2);
  
        int money = 5000;
        if (money > 5000) {
            leader1.examine();   // Need to be approved by the big leader first
        } else{ leader2.examin(); }}}Copy the code