Design mode responsibility chain mode

Posted by thunderdogg on Thu, 06 Jan 2022 13:03:24 +0100

catalogue

preface:

Definition and characteristics:

Structure and Implementation:

give an example:

preface:

In the real world, many objects do not exist independently, and the behavior change of one object may lead to the behavior change of one or more other objects. For example, when the price of a commodity rises, some businesses will be happy and consumers will be sad; Also, when we drive to the intersection, we will stop at the red light and go at the green light. There are many examples, such as stock prices and stock market, WeChat official account and WeChat users, weather bureau weather forecast and listeners, thieves and police.

This is also true in the software world. For example, the relationship between data in Excel and line chart, pie chart and histogram; The relationship between model and view in MVC mode; Event source and event handler in the event model. All this is very convenient if implemented in observer mode.

Definition and characteristics:

The definition of Observer mode: it means that there is a one to many dependency between multiple objects. When the state of an object changes, all objects that depend on it are notified and automatically updated. This mode is sometimes called publish subscribe mode and model view mode. It is an object behavior mode.

Its main disadvantages are as follows.

  1. It reduces the coupling relationship between the target and the observer, which is an abstract coupling relationship. Comply with the principle of dependency inversion.

  2. A trigger mechanism is established between the target and the observer.

Structure and Implementation:

The responsibility chain model mainly includes the following roles.

  1. Abstract Handler role: define an interface for processing requests, including abstract processing methods and a subsequent connection.

  2. Concrete Handler role: implement the processing method of the abstract handler to judge whether the request can be processed. If the request can be processed, process it. Otherwise, transfer the request to its successor.

  3. Client role: create a processing chain and submit a request to the specific handler object of the chain head. It does not care about the processing details and the transmission process of the request.

give an example:

Requirements:

Class diagram:

Code implementation:

//Request class
public class PurchaseRequest {
    private int type = 0;//Request type
    private float price = 0.0f;//Requested amount
    private int id = 0;//Request number

    //constructor 
    public PurchaseRequest(int type, float price, int id) {
        this.type = type;
        this.price = price;
        this.id = id;
    }

    public int getType() {
        return type;
    }

    public float getPrice() {
        return price;
    }

    public int getId() {
        return id;
    }
}

//Abstract handler
public abstract class Approver {
    //Next processor
    Approver approver;
    //name
    String name;

    public Approver(String name) {
        this.name = name;
    }

    //Set next processor
    public void setApprover(Approver approver) {
        this.approver = approver;
    }

    //The subclass of the method for processing request approval, that is, the specific handler, completes the processing. It is abstract here
    public abstract void processRequest(PurchaseRequest p);
}

//Specific handler 1
public class DepartmentApprover extends Approver {

    public DepartmentApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest p) {
        if (p.getPrice() < 3000) {
            System.out.println("Request number:"+ p.getId() + "\t cover"+ this.name + "handle");
        }else {
            approver.processRequest(p);
        }
    }
}

//Specific handler 2
public class CollegeApprover extends Approver {

    public CollegeApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest p) {
        if (p.getPrice() > 5000 && p.getPrice() <= 10000) {
            System.out.println("Request number:" + p.getId() + "\t cover" + this.name + "handle");
        } else {
            approver.processRequest(p);
        }
    }
}

//Specific handler 3
public class ViceSchoolMasterApprover extends Approver{
    public ViceSchoolMasterApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest p) {
        if (p.getPrice() > 10000 && p.getPrice() <= 30000) {
            System.out.println("Request number:" + p.getId() + "\t cover" + this.name + "handle");
        } else {
            approver.processRequest(p);
        }
    }
}

//Specific handler 4
public class SchoolMasterApprover extends Approver{
    public SchoolMasterApprover(String name) {
        super(name);
    }

    @Override
    public void processRequest(PurchaseRequest p) {
        if (p.getPrice() > 30000) {
            System.out.println("Request number:"+ p.getId() + "\t cover"+ this.name + "handle");
        }else {
            approver.processRequest(p);
        }
    }
}

//Customer class
public class Client {
    public static void main(String[] args) {
        //Create a request
        PurchaseRequest pr = new PurchaseRequest(1,31000,1);
        //Create relevant handler
        DepartmentApprover departmentApprover = new DepartmentApprover("Director Zhang");
        CollegeApprover collegeApprover = new CollegeApprover("President Li");
        ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("Vice president Wang");
        SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("Principal Tong");
        //Set next handler
        departmentApprover.setApprover(collegeApprover);
        collegeApprover.setApprover(viceSchoolMasterApprover);
        viceSchoolMasterApprover.setApprover(schoolMasterApprover);
        schoolMasterApprover.setApprover(departmentApprover);

        //Processing requests
        departmentApprover.processRequest(pr);

    }
}

Operation results:

The request number is: 1. It was handled by President Tong

Topics: Design Pattern