## 1. 什么是责任链设计模式
## 2. 如何使用责任链设计模式
## 3. 代码
public abstract class AbstractRequest {
private Object object;
public AbstractRequest(Object object) {
this.object=object; }
/**
* 具体的内容对象
* @return
*/
public Object getContent() { return object; }
/**
* 获取请求级别
*/
public abstract int getRequestLevel();
}
public class Client {
public static void main(String[] args) {
Handler handler1=new Hander1();
Handler handler2=new Handler2();
Handler handler3=new Handler3();
handler1.nextHandler=handler2;
handler2.nextHandler=handler3;
AbstractRequest request3=new Request2("请求1");
AbstractRequest request4=new Request3("请求2");
handler1.handleRequest(request3);
handler2.handleRequest(request4);
}
}
public class Hander1 extends Handler {
@Override
public void handle(AbstractRequest abstractRequest) {
System.out.println("----handle1 处理请求: "+abstractRequest.getRequestLevel()); }
@Override
public int getHandleLevel() {
return 1;
}
}
public abstract class Handler {
public Handler nextHandler;
public void handleRequest(AbstractRequest abstractRequest) {
if (getHandleLevel() == abstractRequest.getRequestLevel()) {
handle(abstractRequest);
} else {
if (nextHandler != null) { nextHandler.handleRequest(abstractRequest);
} else { System.out.println("----> 所有的处理对象都不能处理它"); }
}
}
/**
* 每个处理者的对象的具体处理方式
* @param abstractRequest
*/
public abstract void handle(AbstractRequest abstractRequest);
/**
* 每个处着对象处理的级别
* @return
*/
public abstract int getHandleLevel();
}
public class Handler2 extends Handler {
@Override
public void handle(AbstractRequest abstractRequest) {
System.out.println("----handle2 处理请求: "+abstractRequest.getRequestLevel());
}
@Override
public int getHandleLevel() {
return 2;
}
}
public class Handler3 extends Handler{
@Override
public void handle(AbstractRequest abstractRequest) {
System.out.println("----handle3 处理请求: "+abstractRequest.getRequestLevel());
}
@Override
public int getHandleLevel() {
return 3;
}
}
public class Request1 extends AbstractRequest {
public Request1(Object object) {
super(object);
}
@Override
public int getRequestLevel() {
return 1;
}
}
public class Request2 extends AbstractRequest {
public Request2(Object object) {
super(object);
}
@Override
public int getRequestLevel() {
return 2;
}
}
public class Request3 extends AbstractRequest {
public Request3(Object object) {
super(object);
}
@Override
public int getRequestLevel() {
return 3;
}
}