链式传送
场景
解耦请求和多个处理者,处理者有循序但是逻辑上无依赖
请求不关心谁来处理,只是交给链,处理者自己决定要不要参与处理
代码
处理器自身维护关系
每个处理器包含下一步的处理器,构造时传入
处理完只有交给下一个处理
Sample1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| abstract class AbstractHandler { protected AbstractHandler next;
public AbstractHandler(AbstractHandler next) { this.next = next; }
public void process(Request request) { handle(request); if (next != null) { next.process(request); } }
protected abstract void handle(Request request); }
class HandlerA extends AbstractHandler { public HandlerA(AbstractHandler next) { super(next); } @Override protected void handle(Request request) { if (canHandle(request)) { System.out.println("AAA"); } } private boolean canHandle(Request request) { return true; } }
class HandlerB extends AbstractHandler { public HandlerB(AbstractHandler next) { super(next); } @Override protected void handle(Request request) { if (canHandle(request)) { System.out.println("BBB"); } } private boolean canHandle(Request request) { return true; } }
|
调用
Sample1 2
| AbstractHandler handler = new HandlerA(new HandlerB(null)); handler.process(new Request());
|
外部列表维护关系
进一步改进,抽象出chain类专门负责传递,处理器类只关注自身
处理器处理逻辑内部调用chain传递给下一个处理器
Sample1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class Request { }
interface Chain { void addHandler(Handler handler); void handle(Request request); }
interface Handler { void handle(Request request, Chain chain); }
class HandlerA implements Handler { @Override public void handle(Request request, Chain chain) { if (canHandle(request)) { System.out.println("AAA"); chain.handle(request); } }
private boolean canHandle(Request request) { return true; } }
class HandlerB implements Handler { @Override public void handle(Request request, Chain chain) { if (canHandle(request)) { System.out.println("BBB"); chain.handle(request); } }
private boolean canHandle(Request request) { return true; } }
class HandlerChain implements Chain { private List<Handler> handlers = new ArrayList<>(); private int index = 0;
@Override public void addHandler(Handler h) { handlers.add(h); }
@Override public void handle(Request request) { if (index == handlers.size()) { return; } Handler h = handlers.get(index); index++; h.handle(request, this); } }
|
调用
Sample1 2 3 4
| Chain chain = new HandlerChain(); chain.addHandler(new HandlerA()); chain.addHandler(new HandlerB()); chain.handle(new Request());
|
优缺点
优点:
- 避免了多个处理逻辑混合在一起,处理器只专注自身逻辑
- 处理器可以灵活增删
应用
Servlet Filter