标签:extends handle info string boolean rgs extend img rri
适用场景如下:
springmvc中的拦截器就用了责任链模式
UML图如下:
其中最为关键位handle类
代码如下:
public abstract class Handle {
protected String name;
protected Handle nextHandle;
public void setName(String name) {
this.name = name;
}
public void setNextHandle(Handle nextHandle) {
this.nextHandle = nextHandle;
}
protected abstract void hand(HandRequest request);
protected abstract boolean isHand(HandRequest request);
protected void handFun(HandRequest request){
if(this.isHand(request)){
this.hand(request);
}else {
System.out.println(this.name+"处理不了,让"+nextHandle.name+"处理");
nextHandle.handFun(request);
}
}
}
AHandle类
public class AHandle extends Handle { @Override protected void hand(HandRequest request) { System.out.println("我是A,正在处理:"+request.getDay()); } @Override protected boolean isHand(HandRequest request) { if(request.getDay()>10){ return false; } return true; } }
Client类调用
public static void main(String[] args) {
Handle aHandle = new AHandle();
aHandle.setName("a");
Handle bHandle = new BHandle();
bHandle.setName("b");
Handle cHandle = new CHandle();
cHandle.setName("c");
//构件责任链
aHandle.setNextHandle(bHandle);
bHandle.setNextHandle(cHandle);
//处理A
HandRequest handRequestA = new HandRequest(1);
aHandle.handFun(handRequestA);
System.out.println("=========================");
//处理B
HandRequest handRequestB = new HandRequest(11);
aHandle.handFun(handRequestB);
System.out.println("=========================");
//处理C
HandRequest handRequestC = new HandRequest(111);
aHandle.handFun(handRequestC);
结果效果如下:
标签:extends handle info string boolean rgs extend img rri
原文地址:https://www.cnblogs.com/yeyongjian/p/8909111.html