阅读量:3
在Java中,Handler模式通常是通过使用接口或抽象类来定义处理程序(Handler)的行为,并且在具体的处理程序实现中调用下一个处理程序以构成一个处理程序链。以下是一个简单的示例来实现Handler模式:
// 定义处理程序接口 public interface Handler { void handleRequest(Request request); void setNextHandler(Handler nextHandler); } // 具体的处理程序实现 public class ConcreteHandlerA implements Handler { private Handler nextHandler; @Override public void handleRequest(Request request) { // 根据具体情况处理请求 if (request.getType() == RequestType.TYPE_A) { System.out.println("Handling request of type A"); } else if (nextHandler != null) { nextHandler.handleRequest(request); } } @Override public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } } public class ConcreteHandlerB implements Handler { private Handler nextHandler; @Override public void handleRequest(Request request) { // 根据具体情况处理请求 if (request.getType() == RequestType.TYPE_B) { System.out.println("Handling request of type B"); } else if (nextHandler != null) { nextHandler.handleRequest(request); } } @Override public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } } // 定义请求类 public class Request { private RequestType type; public Request(RequestType type) { this.type = type; } public RequestType getType() { return type; } } // 定义请求类型枚举 public enum RequestType { TYPE_A, TYPE_B } // 使用Handler模式处理请求 public class Client { public static void main(String[] args) { Handler handlerA = new ConcreteHandlerA(); Handler handlerB = new ConcreteHandlerB(); handlerA.setNextHandler(handlerB); Request request1 = new Request(RequestType.TYPE_A); handlerA.handleRequest(request1); Request request2 = new Request(RequestType.TYPE_B); handlerA.handleRequest(request2); } }
在上面的示例中,我们定义了Handler接口和两个具体的处理程序实现ConcreteHandlerA和ConcreteHandlerB。在Client类中,我们创建了两个处理程序实例,并通过setNextHandler方法将它们连接成一个处理程序链。然后我们创建了两个不同类型的请求,并交给处理程序链来处理。根据请求的类型,处理程序链会依次调用各个处理程序来处理请求。