我正在尝试使用以下参考来实现管道设计模式:https://java-design-patterns.com/patterns/pipeline/和 https://medium.com/@deepakbapat/the-pipeline-design-pattern-in-java-831d9ce2fe21
我创建了下面的示例类来调试和理解流程 .当触发PipelineRunner.class
中的调用jobPipeline.execute(12);
时,只有第一步的方法应该正确执行?但是为什么其他步骤(第二步和第三步)也一个接一个地执行呢?
步.class
public interface Step<I, O> {
O executeStep(I stepData);
}
管道.class
public class Pipeline<I, O> {
private final Step<I, O> current;
public Pipeline(Step<I, O> current) {
this.current = current;
}
public <K> Pipeline<I, K> next(Step<O, K> step) {
return new Pipeline<>(input -> step.executeStep(current.executeStep(input)));
}
public O execute(I input) {
return current.executeStep(input);
}
}
管道运行器.class
public class PipelineRunner {
public static void main(String[] args) {
Step<Integer, Integer> firstStep = x->{ System.out.println("First step");
return 2; };
Step<Integer, Integer> secondStep = x->{ System.out.println("Second step");
return 2; };
Step<Integer, Integer> thirdStep = x->{ System.out.println("Third step");
return 2; };
var jobPipeline = new Pipeline<>(firstStep)
.next(secondStep)
.next(thirdStep);
jobPipeline.execute(12); //How rest of steps( second and third step) are executed with this single call on the jobPipeline object?
}
}
输出:
First step
Second step
Third step
在这一行中:
step.executeStep(current.executeStep(input))
current.executeStep
被执行,然后step.executeStep
以便可以传入其结果。 这与Math.abs(1+2)
在将1+2=3
传递给Math.abs
之前对其进行评估没有什么不同。