责任链模式
个人博客
责任链模式
模式介绍
责任链模式是行为型设计模式之一。
模式定义
使多个对象都有机会处理请求,从而避免了请求的发送者和接收者间的耦合。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
使用场景
-
多个对象可以处理同一请求,但具体由哪个对象处理则在运行时动态决定。
-
在请求处理者不明确的情况下向多个对象的一个提交请求。
-
需要动态指定 组对象处理请求。
简单使用
定义抽象请求类
public abstract class AbstractRequest {
/**
* 处理对象
*/
private Object obj;
public AbstractRequest(Object obj) {
this.obj = obj;
}
/**
* 获取处理对象
* @return
*/
public Object getContent() {
return obj;
}
/**
* 获取请求级别
* @return
*/
public abstract int getRequestLevel();
}
定义抽象处理类
public abstract class AbstractHandler {
/**
* 下一个处理者
*/
AbstractHandler nextHandler;
/**
* 获取处理级别
*
* @return
*/
abstract int getHandlerLevel();
/**
* 处理请求
*
* @param request
*/
abstract void handle(AbstractRequest request);
/**
* 统一处理
*
* @param 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());
}
}
}
}
定义具体请求类
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;
}
}
定义具体处理类
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());
}
}
调用
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);
}
输出结果
Handler1 handle request:1
Handler2 handle request:2
All of handler can not handle the request:3
Android代码搬运工一枚,欢迎留言讨论交流!
个人主页:http://www.milovetingting.cn
个人主页:http://www.milovetingting.cn