This article describes the use of responsibility chain mode for students to take leave. Share it for your reference, as follows:
1. Pattern definition
In the chain of responsibility model, many objects are connected by references to their next home by each object, forming a chain. The client application request is passed on this chain until an object on the chain decides to process the request. The client making this request does not know which object on the chain ultimately handles the request, which allows the system to dynamically reorganize the chain and assign responsibilities without affecting the client.
(1) Abstract processor role: define an interface for processing requests. If needed, the interface can define a method to set and return the reference to the next home. This role is usually implemented by a Java abstract class or Java interface.
(2) Specific processing role: After receiving the request, the specific processor can choose to process the request or pass the request to the next home.
2. Model examples
1 Pattern Analysis
We borrow students' leave to illustrate this model
2 Static class diagram of responsibility chain pattern
3 Code Examples
3.1 Student Interface IStudent
package com.demo.chain.message;/** * Student interface* * @author * */public interface IStudent { /** * Get the student's condition status* * 0: Small things (the class monitor can handle it) * * 1: The class monitor cannot handle things that the teacher can handle* * 2: The teacher cannot handle things that the principal can handle* * * */ public int getState(); /** * Get the student's leave message* * @return */ public String getRequestMessage();}3.2 Students realize a Student
package com.demo.chain.message;/** * Student implementation class* * @author * */public class Student implements IStudent { // Size of the condition private int state = -1; // Farewell message private final String message; public Student(int state, String message) { this.state = state; this.message = message; } /** * Get the student leave status* * 0: Small things (the class monitor can handle) * * 1: The class monitor cannot handle things that the teacher can handle* * * 2: The teacher cannot handle things that the principal can handle* * * */ public int getState() { return this.state; } /** * Get student leave message* * @return */ public String getRequestMessage() { return this.message; }}3.3 Abstract Processing Interface-IHandler
package com.demo.chain.handle;import com.demo.chain.message.IStudent;/** * Abstract Processor Interface* * @author * */public interface IHandler { // Process request public void handleRequest(IStudent student); // Set the next handler public void setHandler(IHandler handler);}3.4 AbstractHandler
package com.demo.chain.handle;import com.demo.chain.message.IStudent;/** * Abstract handler* * @author * */public abstract class AbstractHandler implements IHandler { // Next handler private IHandler handler; // Leave level private int state = -1; // Constructor setting level public AbstractHandler(int state) { this.state = state; } // Handle requests to the subclass to handle specific processing public abstract void process(IStudent student); // Handle requests public void handleRequest(IStudent student) { // If the student object exists if (student != null) { if (this.state == student.getState()) { // If the leave level is consistent with the current, the current object will be processed this.process(student); } else { if (this.handler != null) { System.out.println("Request the superior leader to reply!"); // If the current object cannot be processed, it will be handed over to the next processor for processing this.handler.handleRequest(student); } } } } } // Set the next processor public void setHandler(IHandler handler) { this.handler = handler; }}3.5 Squad LeaderHandler
package com.demo.chain.handle;import com.demo.chain.message.IStudent;/** * Abstract handler* * @author * */public abstract class AbstractHandler implements IHandler { // Next handler private IHandler handler; // Leave level private int state = -1; // Constructor setting level public AbstractHandler(int state) { this.state = state; } // Handle requests to the subclass to handle specific processing public abstract void process(IStudent student); // Handle requests public void handleRequest(IStudent student) { // If the student object exists if (student != null) { if (this.state == student.getState()) { // If the leave level is consistent with the current, the current object will be processed this.process(student); } else { if (this.handler != null) { System.out.println("Request the superior leader to reply!"); // If the current object cannot be processed, it will be handed over to the next processor for processing this.handler.handleRequest(student); } } } } } // Set the next processor public void setHandler(IHandler handler) { this.handler = handler; }}3.6 Teacher-TeacherHandler
package com.demo.chain.impl;import com.demo.chain.handle.AbstractHandler;import com.demo.chain.message.IStudent;/** * Teacher handler* * @author * */public class TeacherHandler extends AbstractHandler { public TeacherHandler() { super(1); } // Subclass specific processing request @Override public void process(IStudent student) { System.out.println("Teacher's reply: " + student.getRequestMessage()); }}3.7 Principal-SchoolMasterHandler
package com.demo.chain.impl;import com.demo.chain.handle.AbstractHandler;import com.demo.chain.message.IStudent;/** * Principal handler* * @author * */public class SchoolMasterHandler extends AbstractHandler { public SchoolMasterHandler() { super(2); } // Subclass specific processing request @Override public void process(IStudent student) { System.out.println("Principal's reply: " + student.getRequestMessage()); }}3.8 Appearance Class 1 ProcessHandler
package com.demo.chain.process;import com.demo.chain.handle.IHandler;import com.demo.chain.impl.SchoolMasterHandler;import com.demo.chain.impl.SquadLeaderHandler;import com.demo.chain.impl.TeacherHandler;import com.demo.chain.message.IStudent;/** * Set the responsibility chain association* * @author * */public class ProcessHandler { // Class leader handler private final IHandler sqmshandler; // Teacher handler private final IHandler techhandler; // Principal handler private final IHandler scmshandler; // Singleton mode private static ProcessHandler processHandler = new ProcessHandler(); /** * Constructor method to establish a responsibility chain for leave processing*/ private ProcessHandler() { // Create processing object// Class leader this.sqmshandler = new SquadLeaderHandler(); // Teacher this.techhandler = new TeacherHandler(); // Principal this.scmshandler = new SchoolMasterHandler(); /** * Establish a chain of responsibility*/ // Set the next handler of the class leader: teacher this.sqmshandler.setHandler(this.techhandler); // Set the next handler of the teacher: principal this.techhandler.setHandler(this.scmshandler); } /** * Get a singleton object instance* * @return */ public static ProcessHandler getInstance() { return processHandler; } /** * Send a leave request* * @param message */ public void sendMessage(IStudent student) { // Send to the first handler: class leader handles this.sqmshandler.handleRequest(student); }}3.9 Client-Client
package com.demo;import java.util.Random;import com.demo.chain.message.IStudent;import com.demo.chain.message.Student;import com.demo.chain.process.ProcessHandler;/** * Main application* * @author * */public class Client { /** * @param args */ public static void main(String[] args) { // Get the appearance object ProcessHandler processHandler = ProcessHandler.getInstance(); // Create a random number object to randomly generate student object Random random = new Random(); for (int i = 0; i < 3; i++) { // Get random number int radom = random.nextInt(3); IStudent student = new Student(radom, "student" + i + "I am sick, I want to take leave!"); System.out.println("################################################################################################################################################################################################################################################################################################################################################################################################################"); // Process the message processHandler.sendMessage(student); System.out.println("#############################################/n"); } }}4 Running results
##########################################################
Request a reply from the superior leader!
Request a reply from the superior leader!
The principal’s reply: Student 0 is sick and wants to take leave!
##########################################################
##########################################################
Request a reply from the superior leader!
Request a reply from the superior leader!
The principal’s reply: Student 1 is sick and wants to take leave!
##########################################################
##########################################################
The class monitor approved: Student 2 is sick and wants to take leave!
##########################################################
III. The design principles of this pattern
1 "Open-Close" principle
2 Single Responsibility Principle
4. Use occasions
(1) There are multiple objects that process the same request. It is still uncertain which one is used to handle it. It is only determined at runtime which object handles it.
(2) The message has multiple recipients, and the receiving object is unclear. You only need to send a message to one of the objects and handle it internally.
(3) Multiple processing objects of the same message may increase or decrease dynamically, and need to be specified dynamically.
5. Static class diagram of responsibility chain pattern
For more Java-related content, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.