dimanche 16 janvier 2022

I have trouble understanding the flow of pipeline design pattern, especially how the chain of steps are executed one after the other?

I am trying to implement pipeline design pattern using reference from : https://java-design-patterns.com/patterns/pipeline/ and https://medium.com/@deepakbapat/the-pipeline-design-pattern-in-java-831d9ce2fe21

I have created example classes as below to debug and understand the flow .When the call jobPipeline.execute(12); in PipelineRunner.class is fired, only first step's method should be executed correct? but how come other steps(second and third steps) are also getting executed one after the other?

Step.class

public interface Step<I, O> {
  O executeStep(I stepData);
}

Pipeline.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);
  }
}

PipelineRunner.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?

  }

}

Ouput:

First step
Second step
Third step

Aucun commentaire:

Enregistrer un commentaire