职责链模式的一个变种如下,执行某一个handler,用当前handler是否执行成功判断是否要执行下一个handler,
首先我们定义一个抽象handler类,如果当前handler执行不成功,且还有下一个handler,则继续往下执行
public abstract class Handler { protected Handler nextHandler; public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } public final void handle(String request) { boolean b = doHandle(request); if (!b && this.nextHandler != null) { nextHandler.handle(request); } } protected abstract boolean doHandle(String request); }
下面实现借助之前解析时间字符串的案例,写三个handler实现类
public class HandlerA extends Handler{ @Override protected boolean doHandle(String request) { try { LocalDate parse = LocalDate.parse(request); System.out.println("HandlerA"); System.out.println(parse); return true; } catch (Exception e) { System.err.println(e.getMessage());; } return false; } } public class HandlerB extends Handler { @Override protected boolean doHandle(String request) { try { LocalDateTime parse = LocalDateTime.parse(request); System.out.println("HandlerB"); System.out.println(parse); return true; } catch (Exception e) { System.err.println(e.getMessage()); } return false; } } public class HandlerC extends Handler { public static final DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); @Override protected boolean doHandle(String request) { try { TemporalAccessor parse = dtFormat.parse(request); System.out.println("HandlerC"); System.out.println(parse); return true; } catch (DateTimeParseException e) { System.err.println(e.getMessage()); } return false; } }
我们定义一个入口函数
public class App { public static void main(String[] args) { Handler handler1 = new HandlerA(); Handler handler2 = new HandlerB(); Handler handler3 = new HandlerC(); handler1.setNextHandler(handler2); handler2.setNextHandler(handler3); String d1="2022-08-08"; String d2="2022-08-08T10:09:09"; String d3="2022年08月08日"; handler1.handle(d3); } }
前面两个handler失败了,最后一个成功了,结果如下
输出:
Text '2022年08月08日' could not be parsed at index 4 Text '2022年08月08日' could not be parsed at index 4 HandlerC {},ISO resolved to 2022-08-08