Java responsibility chain pattern template code sharing
- 2020-12-19 21:05:53
- OfStack
This article shared 1 Java programming responsibility chain template code, the code has detailed comments, you can refer to. The details are as follows:
// Abstract handler
public abstract class Handler{
private Handler nextHandler;
// Each handler must process the request
public final Response handleMessage(Request request){
Response response = null;
// Determine your own level of processing
if(this.getHandlerLevel().equals(request.getRequestLevel())){
response = this.echo(request);
}else{
// Determine if there is 1 A handler
if(this.nextHandler != null){
response = this.nextHandler.handleMessage(request);
}else{
// There is no proper handler
}
}
return response;
}
// Settings 1 Who are the handlers
public void setNext(Handler _handler){
this.nextHandler = _handler;
}
// Every handler has one 1 Individual processing levels
protected abstract Level getHandlerLevel();
// Each handler must implement the processing task
protected abstract Response echo(Request request);
}
// Concrete handler 1
publlic class ConcreteHandler1 extends Handler{
// Define your own processing logic
protected Response echo(Request request){
// Completion processing logic
return null;
}
// Set your own processing level
protected Level getHandlerLevel(){
// Set your own processing level
return null;
}
}
// Concrete handler 2
publlic class ConcreteHandler2 extends Handler{
// Define your own processing logic
protected Response echo(Request request){
// Completion processing logic
return null;
}
// Set your own processing level
protected Level getHandlerLevel(){
// Set your own processing level
return null;
}
}
// Concrete handler 3
publlic class ConcreteHandler3 extends Handler{
// Define your own processing logic
protected Response echo(Request request){
// Completion processing logic
return null;
}
// Set your own processing level
protected Level getHandlerLevel(){
// Set your own processing level
return null;
}
}
// The code for the framework in the schema
public class Level{
// define 1 Ten request and processing levels
}
public class Request{
// Request level
public Level getRequestLevel(){
return null;
}
}
public class Response{
// Process the data of the returnee
}
// Scene: the 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();
// Sets the sequence of stages in the chain 1-->2-->3
handler1.setNext(handler2);
handler2.setNext(handler3);
// Submit a request
Response response = handler.handleMessage(new Request());
}
}
conclusion
That is the end of this article on Java responsibility chain pattern template code sharing, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!