责任链模式--行为模式
Posted 大佬健
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了责任链模式--行为模式相关的知识,希望对你有一定的参考价值。
适用场景如下:
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);
结果效果如下:
以上是关于责任链模式--行为模式的主要内容,如果未能解决你的问题,请参考以下文章