This article shares a template code for Java programming responsibility chain pattern. There are detailed comments in the code, which you can refer to. The details are as follows:
//Abstract handler public abstract class Handler{ private Handler nextHandler; //Every handler must handle the request public final Response handleMessage(Request request){ Response response = null; //Judge whether it has its own processing level if(this.getHandlerLevel().equals(request.getRequestLevel())){ response = this.echo(request); }else{ //Judge whether there is a next handler if(this.nextHandler != null){ response = this.nextHandler.handleMessage(request); }else{ //No proper handler} } return response; } //Set who the next handler is public void setNext(Handler _handler){ this.nextHandler = _handler; } //Each processor has a processing level protected abstract Level getHandlerLevel(); //Every processor must implement the processing task protected abstract Response echo(Request request); } //Specific processor1 public class ConcreteHandler1 extends Handler{ //Define your own processing logic protected Response echo(Request request){ //Complete the processing logic return null; } //Set your own processing level protected Level getHandlerLevel(){ //Set your own processing level return null; } } //Specific processor 2 public class ConcreteHandler2 extends Handler{ //Define your own processing logic protected Response echo(Request request){ //Complete the processing logic return null; } //Set your own processing level protected Level getHandlerLevel(){ //Set your own processing level return null; } } //Specific processor 3 public class ConcreteHandler3 extends Handler{ //Define your own processing logic protected Response echo(Request request){ //Complete the processing logic return null; } //Set your own processing level protected Level getHandlerLevel(){ //Set your own processing level return null; } } //Code about the framework in the mode public class Level{ //Define a request and processing level} public class Request{ //Request level public Level getRequestLevel(){ return null; } } } public class Response{ //Process the data of the returner} //Scene class public class Client{ public static void main(String[] args){ //Declare all processing nodes Handler handler1 = new ConcreteHandler1(); Handler handler2 = new ConcreteHandler2(); Handler handler2 = new ConcreteHandler3(); //Set the stage order in the chain 1-->2-->3 handler1.setNext(handler2); handler2.setNext(handler3); //Submit request Response response = handler.handleMessage(new Request()); } }Summarize
The above is all the content of this article about the Java responsibility chain pattern template code sharing, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!