责任链模式,是用于避免请求发送者与多个请求处理者耦合在一起,让所有请求的处理者持有下一个对象的引用,从而将请求串联成一条链,在有请求发生时,可将请求沿着这条链传递,直到遇到该对象的处理器。用户只需将请求发送到责任链上即可,无须关心请求的处理细节和传递过程。
责任链模式包含以下三种角色。
- Handler 接口:用于规定在责任链上具体要执行的方法。
- AbstractHandler 抽象类:持有Handler实例并通过setHandler()和getHandler()将各个具体的业务Handler串联成一个责任链,客户端上的请求在责任链上执行。
- Handler 业务处理类:用户根据具体的业务需求实现的业务逻辑。
服务端要针对客户端的请求实现用户鉴权、业务调用、结果反馈流程 UML设计图如下:
1)Handler 接口:
public interface Handler {void operator();
}
2)AbstractHandler 抽象类:
public abstract class AbstractHandler {private Handler handler;public Handler getHandler() {return handler;}public void setHandler(Handler handler) {this.handler = handler;}
}
3)Handler 业务处理类:
@Slf4j
public class AuthHandler extends AbstractHandler implements Handler {private String name;public AuthHandler(String name) {this.name = name;}@Overridepublic void operator() {log.info("user auth ...");if (getHandler() != null) {getHandler().operator();}}
}
@Slf4j
public class BusinessHandler extends AbstractHandler implements Handler {private String name;public BusinessHandler(String name) {this.name = name;}@Overridepublic void operator() {log.info("business handler ...");if (getHandler() != null) {getHandler().operator();}}
}
@Slf4j
public class ResponseHandler extends AbstractHandler implements Handler {private String name;public ResponseHandler(String name) {this.name = name;}@Overridepublic void operator() {log.info("response handler ...");if (getHandler() != null) {getHandler().operator();}}
}
4)责任链模式测试类:
public class ResponsibilityChainDemoTest {public static void main(String[] args) {AuthHandler authHandler = new AuthHandler("auth");BusinessHandler businessHandler = new BusinessHandler("buss");ResponseHandler responseHandler = new ResponseHandler("resp");authHandler.setHandler(businessHandler);businessHandler.setHandler(responseHandler);authHandler.operator();}
}
5)打印结果: