責任鏈模式【行為模式】
阿新 • • 發佈:2018-12-23
責任鏈模式
Avoid coupling the sender of a request to its receiver by giving more than one object
a chance to handle the request. Chain the receiving objects and pass the request along
until an object handle it.
避免請求傳送方與請求處理方耦合,責任鏈模式使得多個物件都有機會處理請求。
將請求處理方連成一條鏈,並將請求沿著處理鏈傳遞,直到有接收者處理該請求為止。
public class ResponsibilityChain { /** * 責任鏈模式: * Avoid coupling the sender of a request to its receiver by giving more than one object * a chance to handle the request. Chain the receiving objects and pass the request along * until an object handle it. * 避免請求傳送方與請求處理方耦合,責任鏈模式使得多個物件都有機會處理請求。 * 將請求處理方連成一條鏈,並將請求沿著處理鏈傳遞,直到有接收者處理該請求為止。 */ @Test public void all() { final ProblemImpl easy = ProblemImpl.builder() .type(ProblemType.EASY) .desc("註解的元註解有哪些").build(); final ProblemImpl middle = ProblemImpl.builder() .type(ProblemType.MIDDLE) .desc("AtomicInteger 實現原理").build(); final ProblemImpl hard = ProblemImpl.builder() .type(ProblemType.HARD) .desc("Jvm 記憶體結構").build(); final IHandle context = HandlerContext.get(); /** * 問題總是從責任鏈的頭部開始執行 */ context.handle(easy); context.handle(middle); context.handle(hard); } } /** * 1)請求處理方法支援的請求型別 */ enum ProblemType { EASY, MIDDLE, HARD, POWER_LESS } /** * 2)請求詳情介面,包括請求型別 */ interface IProblem { ProblemType type(); String desc(); } /** * 3)抽象的處理者,該處理者封裝了請求處理過程。 */ @Data @Slf4j @RequiredArgsConstructor abstract class AHandler { private final ProblemType type; private final AHandler nextHandler; public final void handle(IProblem problem) { if (type == problem.type()) { log.info("問題被解決 {}", problem.desc()); } else if (nextHandler != null) { nextHandler.handle(problem); } else { log.info("問題無人解決"); } } } /** * 4)具體的請求實現 */ @Builder @AllArgsConstructor class ProblemImpl implements IProblem { private final ProblemType type; private final String desc; @Override public ProblemType type() { return type; } @Override public String desc() { return desc; } } /** * 5)具體的請求處理者 */ class EasyHanlder extends AHandler { public EasyHanlder(AHandler nextHandler) { super(ProblemType.EASY, nextHandler); } private EasyHanlder(ProblemType type, AHandler nextHandler) { super(type, nextHandler); } } /** * 6)具體的請求處理者 */ class HardHandler extends AHandler { public HardHandler(AHandler nextHandler) { super(ProblemType.HARD, nextHandler); } private HardHandler(ProblemType type, AHandler nextHandler) { super(type, nextHandler); } } /** * 7)對外提供的門面介面 */ interface IHandle{ void handle(IProblem problem); } /** * 8)處理請求的上下文 */ class HandlerContext implements IHandle { public final AHandler handler; private static final HandlerContext CONTEXT = new HandlerContext(); private HandlerContext() { handler = new EasyHanlder(new HardHandler(null)); } public static final HandlerContext get() { return CONTEXT; } @Override public void handle(IProblem problem) { handler.handle(problem); } }