public class BasicValve implements Valve {
protected Valve next = null;
public Valve getNext() {
return next;
}
public void invoke(String handling) {
handling=handling.replaceAll("aa", "bb");
System.out.println("基础阀门处理完后:" + handling);
}
public void setNext(Valve valve) {
this.next = valve;
}
}
④ 第二个阀门,将传入的字符串中”11”替换成”22”
public class SecondValve implements Valve {
protected Valve next = null;
public Valve getNext() {
return next;
}
public void invoke(String handling) {
handling = handling.replaceAll("11", "22");
System.out.println("Second阀门处理完后:" + handling);
getNext().invoke(handling);
}
public void setNext(Valve valve) {
this.next = valve;
}
}
⑤ 第三个阀门,将传入的字符串中”zz”替换成”yy”
public class ThirdValve implements Valve {
protected Valve next = null;
public Valve getNext() {
return next;
}
public void invoke(String handling) {
handling = handling.replaceAll("zz", "yy");
System.out.println("Third阀门处理完后:" + handling);
getNext().invoke(handling);
}
public void setNext(Valve valve) {
this.next = valve;
}
}
⑥ 管道,我们一般的操作是先通过setBasic设置基础阀门,接着按顺序添加其他阀门,执行时的顺序是:先添加进来的先执行,最后才执行基础阀门。
public class StandardPipeline implements Pipeline {
protected Valve first = null;
protected Valve basic = null;
public void addValve(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);
break;
}
current = current.getNext();
}
}
}
public Valve getBasic() {
return basic;
}
public Valve getFirst() {
return first;
}
public void setBasic(Valve valve) {
this.basic = valve;
}
}
⑦ 测试类
public class Main {
public static void main(String[] args) {
String handling="aabb1122zzyy";
StandardPipeline pipeline = new StandardPipeline();
BasicValve basicValve = new BasicValve();
SecondValve secondValve = new SecondValve();
ThirdValve thirdValve = new ThirdValve();
pipeline.setBasic(basicValve);
pipeline.addValve(secondValve);
pipeline.addValve(thirdValve);
pipeline.getFirst().invoke(handling);
}
}
输出的结果如下:
Second阀门处理完后:aabb2222zzyy Third阀门处理完后:aabb2222yyyy 基础阀门处理完后:bbbb2222yyyy
这就是管道模式,在管道中连接一个或多个阀门,每个阀门负责一部分逻辑处理,数据按规定的顺序往下流。此模式分解了逻辑处理任务,可方便对某任务单元进行安装拆卸,提高了流程的可扩展性、可重用性、机动性、灵活性。









