【Java 责任链模式实例】
责任链模式是一种行为设计模式,它允许你将请求沿着处理者链进行发送,直到有一个处理者处理它为止。在责任链模式中,每个处理者都是相互独立的对象,并且每个处理者都负责对请求进行处理。如果当前处理者不能处理请求,则它将请求传递给下一个处理者,直到请求被处理为止。
责任链模式通常包含以下角色:
抽象处理者(Handler):定义处理请求的接口和方法,同时保存下一个处理者的引用。 具体处理者(ConcreteHandler):继承或实现抽象处理者的接口,实现其处理方法,如果自己无法处理请求,则将请求传递给下一个处理者。 客户端(Client):创建一个处理者链并将请求发送给该链。
下面是一个 Java 实现责任链模式的示例:
// 抽象处理者 public abstract class Handler { protected Handler nextHandler; // 下一个处理者 public void setNextHandler(Handler handler) { this.nextHandler = handler; } // 处理请求的方法 public abstract void handleRequest(Request request); } // 具体处理者A public class ConcreteHandlerA extends Handler { @Override public void handleRequest(Request request) { if (request.getType() == RequestType.TYPE1) { System.out.println("ConcreteHandlerA handling request..."); } else if (nextHandler != null) { nextHandler.handleRequest(request); } } } // 具体处理者B public class ConcreteHandlerB extends Handler { @Override public void handleRequest(Request request) { if (request.getType() == RequestType.TYPE2) { System.out.println("ConcreteHandlerB handling request..."); } else if (nextHandler != null) { nextHandler.handleRequest(request); } } } // 请求类型 public enum RequestType { TYPE1, TYPE2 } // 请求 public class Request { private RequestType type; public Request(RequestType type) { this.type = type; } public RequestType getType() { return type; } } // 客户端 public class Client { public static void main(String[] args) { Handler handler1 = new ConcreteHandlerA(); Handler handler2 = new ConcreteHandlerB(); handler1.setNextHandler(handler2); Request request1 = new Request(RequestType.TYPE1); handler1.handleRequest(request1); Request request2 = new Request(RequestType.TYPE2); handler1.handleRequest(request2); } }
在这个例子中,Handler 定义了处理请求的接口,并且保存了下一个处理者的引用。ConcreteHandlerA 和 ConcreteHandlerB 分别实现了 Handler 接口,并且在处理请求时,如果自己无法处理请求,则将请求传递给下一个处理者。客户端通过创建一个处理者链,并将请求发送给该链来触发处理者链的处理过程。
责任链模式的优点如下:
总之,责任链模式能够提高系统的灵活性和可扩展性,降低系统的耦合度,使得系统更加易于维护和扩展。