管道模式属于设计模式中责任链模式的变种,Tomcat定义了Pipeline(管道)和Value(阀) 两个接口,前者用于构造责任链,后者代表责任链上的每个处理器。从字面意思理解这两个接口所扮演的角色–来自客户端的请求就像流经管道的水,如图所示:
经过每个阀门进行处理,其设计如图所示:
Pipeline中维护了一个基础的Valve,它始终位于Pipeline的末端(即最后执行),封装了具体的请求处理和输出响应的过程。然后通过addValve()方法,我们可以为Pipeline添加其他的Valve。后添加的Valve位于基础的Valve之前,并且按照添加顺序执行,Pipeline通过获得首个Valve来启动整个链条的执行。
下面写一个管道模式示例:
阀门接口:
//阀门接口
public interface Valve {
public Valve getNext();
public void setNext(Valve valve);
public void invoke(String handing);
}
管道接口:
//管道接口
public interface Pipeline {
//获取第一个阀门
public Valve getFirst();
public Valve getBasic();
//设置阀门
public void setBasic(Valve valve);
//添加阀门
public void addVave(Valve valve);
}
基础阀门:
public class StandardValve implements Valve {
protected Valve next =null;
@Override
public Valve getNext() {
return next;
}
@Override
public void setNext(Valve valve) {
this.next =valve;
}
@Override
public void invoke(String request) {
request = request+"xxoo,";
System.out.println("基础阀门处理");
}
}
管道实现类:
public class StandardPipeline implements Pipeline {
//阀门(非基础,定义一个first)
protected Valve first = null;
//基础阀门
protected Valve basic = null;
@Override
public Valve getBasic() {
return basic;
}
@Override
public void setBasic(Valve valve) {
this.basic=valve;
}
@Override
public Valve getFirst() {
return first;
}
//添加阀门,链式构建阀门的执行顺序(先定制、最后基础阀门)
@Override
public void addVave(Valve valve) {
if(first == null){
first = valve;
valve.setNext(basic);
}else{
Valve current =first;
while(current !=null){
if(current.getNext() == basic){
current.setNext(valve);
valve.setNext(basic);
}
current = current.getNext();
}
}
}
}
定制阀门1:
public class FirstValve implements Valve {
protected Valve next =null;
@Override
public Valve getNext() {
return next;
}
@Override
public void setNext(Valve valve) {
this.next =valve;
}
@Override
public void invoke(String request) {
System.out.println("第一个定制阀门处理!");
getNext().invoke(request);
}
}
定制阀门2:
public class SecondValve implements Valve {
protected Valve next =null;
@Override
public Valve getNext() {
return next;
}
@Override
public void setNext(Valve valve) {
this.next =valve;
}
@Override
public void invoke(String request) {
System.out.println("第二个定制阀门处理!");
getNext().invoke(request);
}
}
测试:
public class Demo {
public static void main(String[] args) {
String request ="这个是一个Servlet请求";
StandardPipeline pipeline = new StandardPipeline();
//三个阀门(一个基础、2个定制)
StandardValve standardValve = new StandardValve();
FirstValve firstValve = new FirstValve();
SecondValve secondValve = new SecondValve();
//设置基础阀门
pipeline.setBasic(standardValve);
//设置非基础阀门
pipeline.addVave(firstValve);
pipeline.addVave(secondValve);
//调用对象管道中的第一个阀门
pipeline.getFirst().invoke(request);
}
}
效果:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/13810.html