责任链模式是一种非常有趣的模式。
责任链模式用于避免请求发送者与多个请求处理者耦合在一起,让所有请求的处理者持有下一格对象的引用,从而将请求串联成一条链,在有请求发生时,可将请求沿着这条链传递,直到遇到该对象的处理器。
(1)定义处理接口
public interface Handler{ void operator(); }
(2)定义抽象处理类
public abstract class AbstractHandler{ private Handler handler; public Handler getHandler() { return handler; } public void setHandler(Handler handler) { this.handler = handler; } }
(3)定义责任类
public class AuthHandler extends AbstractHandler implements Handler{ private final static Log logger = LogFactory.getLog(this.getClass()); private String name; public AuthHandler(String name){ this.name = name; } @Override public void operator(){ logger.info("user auth..."); if (getHandler() != null){ getHandler().operator(); } } } public class BusinessHandler extends AbstractHandler implements Handler{ private final static Log logger = LogFactory.getLog(this.getClass()); private String name; public BusinessHandler(String name){ this.name = name; } @Override public void operator(){ logger.info("business info handler ..."); if (getHandler() != null){ getHandler().operator(); } } } public class ResponseHandler extends AbstractHandler implements Handler{ private final static Log logger = LogFactory.getLog(this.getClass()); private String name; public ResponseHandler(String name){ this.name = name; } @Override public void operator(){ logger.info("response ..."); if (getHandler() != null){ getHandler().operator(); } } }
(4)使用责任链模式
public static void main(String[] args){ AuthHandler authHandler = new AuthHandler("auth"); BusinessHandler businessHandler = new BusinessHandler("business"); ResponseHandler responseHandler = new ResponseHandler("response"); authHandler.setHandler(businessHandler); businessHandler.setHandler(responseHandler); }