深入探索Java设计模式:责任链模式解析与实践

时间:2024-10-13 11:15:11
// 抽象处理者 public abstract class Handler { protected Handler successor; public void setSuccessor(Handler successor) { this.successor = successor; } public abstract void handleRequest(Request request); } // 具体处理者 public class ConcreteHandler1 extends Handler { @Override public void handleRequest(Request request) { if (request.getType().equals("Type1")) { System.out.println("ConcreteHandler1 handles the request"); } else if (successor != null) { successor.handleRequest(request); } } } public class ConcreteHandler2 extends Handler { @Override public void handleRequest(Request request) { if (request.getType().equals("Type2")) { System.out.println("ConcreteHandler2 handles the request"); } else if (successor != null) { successor.handleRequest(request); } } } // 客户端 public class Client { public static void main(String[] args) { Handler handler1 = new ConcreteHandler1(); Handler handler2 = new ConcreteHandler2(); handler1.setSuccessor(handler2); Request request1 = new Request("Type1"); Request request2 = new Request("Type2"); handler1.handleRequest(request1); handler1.handleRequest(request2); } }