责任链
每个审批者作为链中的处理节点只处理一件事情,比如servlet过滤器
· 一般和建造者结合
import java.util.ArrayList;
import java.util.List;
interface Handler {
//实现类自己实现,放行返回true,中止返回false
boolean handle(Object param);
}
class HandlerChain {
private final List<Handler> handlers;
private HandlerChain(List<Handler> handlers) {
this.handlers = handlers;
}
public static class Builder {
private final List<Handler> handlers = new ArrayList<>();
public HandlerChain.Builder next(Handler handler) {
handlers.add(handler);
return this;
}
public HandlerChain build() {
return new HandlerChain(handlers);
}
}
public void doChain(Object param) {
for (Handler handler : handlers) {
if (!handler.handle(param)) {
break;
}
}
}
public void reverseDoChain(Object param) {
for (int i = handlers.size() - 1; i >= 0; i--) {
if (!handlers.get(i).handle(param)) {
break;
}
}
}
}
class Main {
public static void main(String[] args) {
HandlerChain handlerChain = new HandlerChain.Builder()
.next(param -> {
System.out.println("A");
return true;
})
.next(param -> {
System.out.println("B");
return false;
})
.next(param -> {
System.out.println("C");
return true;
})
.build();
handlerChain.doChain(null);
System.out.println();
handlerChain.reverseDoChain(null);
}
}