使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系,
将这些对象形成一条链,并沿着这条链传递该请求,直到有对象处理它为止
- 抽象处理者
public abstract class Handler {
//持有下一个处理者的引用这是很关键的
public Handler nextHandler;
public void handleRequest(AbstractRequest abstractRequest){
if(getHandleLeve()==abstractRequest.getRequestLeve()){
handle(abstractRequest);
}else {
if(null!=nextHandler){
nextHandler.handleRequest(abstractRequest);
}else {
System.out.print("链式调用结束");
}
}
}
/**
* 每个对象的处理方式
* @param abstractRequest
*/
public abstract void handle(AbstractRequest abstractRequest);
/**
* 每个对象的处理级别
* @return
*/
public abstract int getHandleLeve();
}
- 具体的处理者(Handler1 ,Handler2,Handler3 雷同)
public class Handler1 extends Handler {
/**
* 处理请求
* @param abstractRequest
*/
@Override
public void handle(AbstractRequest abstractRequest) {
System.out.print("Handler1---处理:"+abstractRequest.getContent());
}
@Override
public int getHandleLeve() {
return 1;
}
}
- 抽象的请求者
public abstract class AbstractRequest {
private Object object;
public AbstractRequest(Object object) {
this.object=object;
}
/**
* 具体的对象内容
* @return
*/
public Object getContent(){
return object;
}
/**
* 获取的请求级别
* @return
*/
public abstract int getRequestLeve();
}
- 具体的请求者(Request1,Request2,Request3雷同)
public class Request1 extends AbstractRequest {
public Request1(Object object) {
super(object);
}
@Override
public int getRequestLeve() {
return 1;
}
}
- 客户端调用
Handler1 handler1=new Handler1();
Handler2 handler2=new Handler2();
Handler3 handler3=new Handler3();
handler1.nextHandler=handler2;//上一个处理者持有下一个处理者的引用 是现成链式调用的必要条件
handler2.nextHandler=handler3;
Request3 request3=new Request3("请求3");
handler1.handleRequest(request3);
6.结果
Handler3---处理:请求3
Process finished with exit code 0
网友评论