什么是责任链模式:
将请求同一类资源的请求对象练成一条链,所提交的请求到某一个链节,如果该链节能处理则不必要往下传,不然则继续传到下一个对象链接去处理。
开发中常见的场景:
1.springmvc的拦截器
2.java中,异常处理机制,抛出异常
3.javascript的事件冒泡机制
责任链例子:
这里的场景是实现一个拦截器demo,所限当然是定义我们的拦截器,然后,使用时,就继承它
/**
* 定义一个拦截器
* @author liuxg
* @date 2016年5月27日 下午6:01:27
*/
public abstract class Interceptor {
protected Interceptor nextChain ;
public void setNextChain(Interceptor nextChain) {
this.nextChain = nextChain;
}
public abstract void beginIntecept(String condition);
}
class Interceptor1 extends Interceptor{
@Override
public void beginIntecept(String condition) {
if ("interceptor1".equals(condition)) {
System.out.println("拦截器到interceptor1");
}else{
System.out.println("interceptor1无法处理,到下一个拦截器");
nextChain.beginIntecept(condition);
}
}
}
class Interceptor2 extends Interceptor{
@Override
public void beginIntecept(String condition) {
if ("interceptor2".equals(condition)) {
System.out.println("拦截器到interceptor2");
}else{
System.out.println("interceptor2无法处理,到下一个拦截器");
nextChain.beginIntecept(condition);
}
}
}
class Interceptor3 extends Interceptor{
@Override
public void beginIntecept(String condition) {
if ("interceptor3".equals(condition)) {
System.out.println("拦截器到interceptor3");
}else{
System.out.println("interceptor3无法处理,到下一个拦截器");
nextChain.beginIntecept(condition);
}
}
}
客户端可以传递一个条件字符串,所有跟其中一个拦截器匹配,则该拦截器处理,如果不行,则传递到下一个拦截器处理
public class Client {
public static void main(String[] args) {
Interceptor interceptor1 = new Interceptor1();
Interceptor interceptor2 = new Interceptor2();
Interceptor interceptor3 = new Interceptor3();
interceptor1.setNextChain(interceptor2);
interceptor2.setNextChain(interceptor3);
interceptor1.beginIntecept("interceptor3");//处理条件
}
}