个人博客
http://www.milovetingting.cn
责任链模式
模式介绍
责任链模式是行为型设计模式之一。
模式定义
使多个对象都有机会处理请求,从而避免了请求的发送者和接收者间的耦合。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
使用场景
多个对象可以处理同一请求,但具体由哪个对象处理则在运行时动态决定。
在请求处理者不明确的情况下向多个对象的一个提交请求。
需要动态指定 组对象处理请求。
简单使用
定义抽象请求类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public abstract class AbstractRequest {
private Object obj;
public AbstractRequest(Object obj) { this.obj = obj; }
public Object getContent() { return obj; }
public abstract int getRequestLevel(); }
|
定义抽象处理类
1 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
| public abstract class AbstractHandler {
AbstractHandler nextHandler;
abstract int getHandlerLevel();
abstract void handle(AbstractRequest request);
public final void handleRequest(AbstractRequest request) { if (getHandlerLevel() == request.getRequestLevel()) { handle(request); } else { if (nextHandler != null) { nextHandler.handleRequest(request); } else { System.out.println("All of handler can not handle the request:" + request.getRequestLevel()); } } }
}
|
定义具体请求类
1 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
| public class Request1 extends AbstractRequest {
public Request1(Object obj) { super(obj); }
@Override public int getRequestLevel() { return 1; }
}
public class Request2 extends AbstractRequest {
public Request2(Object obj) { super(obj); }
@Override public int getRequestLevel() { return 2; }
}
public class Request3 extends AbstractRequest {
public Request3(Object obj) { super(obj); }
@Override public int getRequestLevel() { return 3; }
}
|
定义具体处理类
1 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
| public class Handler1 extends AbstractHandler {
@Override int getHandlerLevel() { return 1; }
@Override void handle(AbstractRequest request) { System.out.println("Handler1 handle request:" + request.getRequestLevel()); }
}
public class Handler2 extends AbstractHandler {
@Override int getHandlerLevel() { return 2; }
@Override void handle(AbstractRequest request) { System.out.println("Handler2 handle request:" + request.getRequestLevel()); }
}
|
调用
1 2 3 4 5 6 7 8 9 10 11
| public static void main(String[] args) { AbstractRequest request1 = new Request1("Request1"); AbstractRequest request2 = new Request2("Request2"); AbstractRequest request3 = new Request3("Request3"); AbstractHandler handler1 = new Handler1(); AbstractHandler handler2 = new Handler2(); handler1.nextHandler = handler2; handler1.handleRequest(request1); handler1.handleRequest(request2); handler1.handleRequest(request3); }
|
输出结果
1 2 3
| Handler1 handle request:1 Handler2 handle request:2 All of handler can not handle the request:3
|