Java design pattern – Chain of responsibility pattern, I think this is worth you to understand the next.

Will be a review ya, will not come to see it together.

Like a sentence: “eight hours for life, eight hours for development”.

If you like it, let’s stick to it!!

With your mutual mian ๐Ÿ˜

Design Mode series:

  • Java Design pattern – singleton pattern
  • Java Design Pattern – Factory Pattern (1) Simple Factory pattern
  • Java Design Pattern – Factory Pattern (2) Factory method pattern
  • Java Design Pattern – Factory Pattern (3) Abstract Factory pattern
  • Java Design pattern – Builder pattern
  • Java Design pattern – Proxy pattern
  • Java Design pattern – Adapter pattern
  • Java Design pattern – Decorator pattern
  • Java Design pattern – Bridge pattern
  • Java Design pattern – Appearance pattern
  • Java Design pattern – Composite pattern
  • Java Design pattern – Share meta pattern
  • Java Design Pattern – Template method pattern
  • Java Design pattern – Policy pattern
  • Java Design pattern – Chain of Responsibility pattern
  • Java Design Pattern – The Mediator pattern
  • Java Design Pattern – Observer Pattern (publish/subscribe pattern)
  • Continuously updated…

One, foreword

1) Introduction:

In the real world, it is common for an event to be processed by multiple objects.

For example, procurement approval process, leave process and so on. For example, if we ask for leave at school, the counselor can only approve it for 1 day, the dean can approve it for 3 to 7 days, and the secretary has to sign it for more than 7 days. We have to get signatures from different teachers according to the number of days we take off, which means we have to remember each teacher’s name, office location, etc., which makes it more difficult. However, the transformation into software design can be achieved by using the chain of responsibility mode, which can be much simpler and much more efficient.

There are many examples of this in software design, such as filters in servlets, and a series of filters in Security. It’s all part of the chain of responsibility.

2) Overview:

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 Chain of Responsibility pattern is defined as follows: in order to avoid the request sender coupling with multiple request handlers, all request handlers are connected in a Chain by remembering the reference of the previous object to the next object; When a request occurs, it can be passed along the chain until an object processes it.

3) Role Structure:

The responsibility chain pattern mainly consists of the following roles.

  1. The role of Abstract Handler: Defines an interface to process a request, including abstract processing methods and a subsequent connection.
  2. The role of Concrete Handler: Implements the processing method of the abstract Handler, determines whether the request can be processed, if it can be processed, and otherwise passes the request to its successor.
  3. The Client role: Creates a processing chain and submits a request to a specific handler object in the header. It does not care about processing details or the delivery of the request.

4) Usage Scenarios:

  1. Multiple objects can handle a request, but which object handles the request is automatically determined at run time.
  2. You can dynamically specify a set of objects to handle requests, or add new handlers.
  3. You need to submit a request to one of multiple handlers without explicitly specifying the request handler.

Ii. Case code

2.1 Cases:

Now need to develop a leave process control system. Leave of less than one day only requires the counselor’s consent; Leave of 1 to 3 days also need the consent of the dean; Requests for 3 to 7 days require the consent of the college secretary.

2.2. Implementation:

/ / missing
public class LeaveRequest {
    private String name;/ / name
    private int num;// Days of absence
    private String content;// Leave content

    public LeaveRequest(String name, int num, String content) {
        this.name = name;
        this.num = num;
        this.content = content;
    }

    public String getName(a) {
        return name;
    }

    public int getNum(a) {
        return num;
    }

    public String getContent(a) {
        returncontent; }}Copy the code
// Handler abstract class
public abstract class Handler {
    protected final static int NUM_ONE = 1;
    protected final static int NUM_THREE = 3;
    protected final static int NUM_SEVEN = 7;

    // The number of days of leave handled by the leader
    private int numStart;
    private int numEnd;

    // There is a leader above the leader
    private Handler nextHandler;

    // Set the number of days for leave to be uncapped
    public Handler(int numStart) {
        this.numStart = numStart;
    }

    // Set the number of days for leave
    public Handler(int numStart, int numEnd) {
        this.numStart = numStart;
        this.numEnd = numEnd;
    }

    // Set the superior leader
    public void setNextHandler(Handler nextHandler){
        this.nextHandler = nextHandler;
    }

    // Submit a request for leave
    public final void submit(LeaveRequest leave){
        if(0= =this.numStart){
            return;
        }

        // If the number of days of leave meets the leader's processing requirements
        if(leave.getNum() >= this.numStart){
            this.handleLeave(leave);

            // If there is a superior and the number of days of leave exceeds the scope of the current leadership
            if(null! =this.nextHandler && leave.getNum() > numEnd){
                this.nextHandler.submit(leave);// Continue to submit
            } else {
                System.out.println("End of process"); }}}// How leaders at all levels handle leave request notes
    protected abstract void handleLeave(LeaveRequest leave);
}
Copy the code
/ / counselor
public class Counselor extends Handler {
    public Counselor(a) {
        // Counsellors handle leave of 1-3 days
        super(Handler.NUM_ONE, Handler.NUM_THREE);
    }

    @Override
    protected void handleLeave(LeaveRequest leave) {
        System.out.println(leave.getName() + "Leave" + leave.getNum() + "Day." + leave.getContent() + "ใ€‚");
        System.out.println("Counselor approval: Agreed."); }}Copy the code
/ / the dean
public class Dean extends Handler {
    public Dean(a) {
        // The dean handles 3-7 days of leave
        super(Handler.NUM_THREE, Handler.NUM_SEVEN);
    }

    @Override
    protected void handleLeave(LeaveRequest leave) {
        System.out.println(leave.getName() + "Leave" + leave.getNum() + "Day." + leave.getContent() + "ใ€‚");
        System.out.println("Dean approval: Agreed."); }}Copy the code
// College Secretary
public class CollegeSecretary extends Handler {
    public CollegeSecretary(a) {
        // The college Secretary deals with leave of absence of more than 7 days
        super(Handler.NUM_SEVEN);
    }

    @Override
    protected void handleLeave(LeaveRequest leave) {
        System.out.println(leave.getName() + "Leave" + leave.getNum() + "Day." + leave.getContent() + "ใ€‚");
        System.out.println("Approved by the College Secretary: Agreed."); }}Copy the code
/ / test class
public class Client {
    public static void main(String[] args) {
        // A leave slip, please
        LeaveRequest leave = new LeaveRequest("Flower".5."Under the weather");

        // Leadership at all levels
        Counselor counselor= new Counselor();
        Dean dean = new Dean();
        CollegeSecretary collegeSecretary = new CollegeSecretary();

        counselor.setNextHandler(dean);// The instructor is headed by the dean
        dean.setNextHandler(collegeSecretary);// The head of the dean is the college secretary
        // The reason for setting the superior leader here is that it can be changed according to actual requirements. If the superior leader is fixed in actual practice, it can be moved to the leader implementation class.

        // Submit an applicationcounselor.submit(leave); }}Copy the code

Third, summary

Advantages:

  1. Reduces the degree of coupling between objects. This pattern makes it unnecessary for an object to know which object is handling its request and chain structure, and for sender and receiver to have explicit information about each other.
  2. The scalability of the system is enhanced. New request handling classes can be added as needed to satisfy the open close principle.
  3. Increased flexibility in assigning responsibilities to objects. As the workflow changes, members in the chain can be dynamically changed or reordered, and responsibilities can be dynamically added or removed.
  4. Chains of responsibility simplify the connection between objects. Each object maintains only one reference to its successors, not all other handlers, which avoids the need for numerous if or ifยท else statements.
  5. Burden sharing. Each class only needs to deal with its own work, should not deal with the next object to complete, clear the scope of responsibility, in line with the single responsibility of the class principle.

Disadvantages:

  1. There is no guarantee that every request will be processed. Because a request has no clear recipient, there is no guarantee that it will be processed, and the request may not be processed all the way to the end of the chain.
  2. For a long chain of responsibilities, the processing of the request may involve multiple processing objects, and the system performance will be affected to some extent.
  3. The rationality of responsibility chain establishment depends on the client to ensure, which increases the complexity of the client, and may lead to system errors due to the wrong setting of responsibility chain, such as circular invocation.

Four, the application

The real application to the place, in fact, many, of course, the most typical is in the Filter this aspect.

If you’ve ever used Security, you know that it is a string of filters that constitute authentication and authorization droplets. Source code is not posted ha, a word or two words say not ha. ~~ (Dog head survival) ๐Ÿ˜‚

Five, talk to yourself

I do not know whether the article is useful or useless, just want to do a share. I hope you can enjoy it and have a good harvest here.

Of course, THERE is no denying that I also want to achieve the kind of happiness of other people’s approval, and I can continue to maintain it.

Hello, be happy every day. See you in the next article.

This series is still being updated…. I’ll be back for sure. ๐Ÿ˜


I didn’t know that until last nightfutureThe original contains a trace of parting smell.