使用流畅的构建器模式,没有用于工作流的内部静态类

时间:2016-10-12 03:08:23

标签: java design-patterns

这是我在Passing 1 to many parameters of same object type

工作的延续

我对此得到了很好的反馈,我相信我已经改进了设计。整个代码位于https://github.com/spakai/flow_input_builder

要求很简单: -

我需要使用以前工作流程中的一个或多个输出为不同的工作流程构建一组输入

我有一组接口

public interface SwfInput {

}

public interface SwfOutput {

}

public interface Workflow<I extends SwfInput, O extends SwfOutput> {

    public O execute(I input);
}

public interface Builder<I extends SwfInput> {
    public I build();

}

现在,假设我有3个流程按顺序执行FlowA-&gt; FlowB-&gt; FlowC

FlowC需要FlowB的强制输出,但只能从FlowA

中选择

所以我有一个FlowCBuilder的实现

public class FlowCInputBuilder implements Builder<FlowCInput> {

    private final FlowBOutput mandatoryflowBOutput;
    private FlowAOutput optionalflowAOutput;

    public FlowAOutput getOptionalflowAOutput() {
        return optionalflowAOutput;
    }

    public FlowCInputBuilder setOptionalflowAOutput(FlowAOutput optionalflowAOutput) {
        this.optionalflowAOutput = optionalflowAOutput;
        return this;
    }

    public FlowCInputBuilder(FlowBOutput mandatoryflowBOutput) {
        this.mandatoryflowBOutput = mandatoryflowBOutput;
    }

    @Override
    public FlowCInput build() {

        FlowCInput input = new FlowCInput();
        input.setMandatoryFromFlowB(mandatoryflowBOutput.getOutput1FromB());

        if (optionalflowAOutput != null) {
            input.setOptionalFromFlowA(optionalflowAOutput.getOutput2FromA());
        }

        return input;       

    }


}

我写的一个测试显示了一个示例用法

 FlowBOutput mandatoryflowBOutput = new FlowBOutput();

 mandatoryflowBOutput.setOutput1FromB("iNeedThis");
 FlowAOutput optionalflowAOutput = new FlowAOutput();
 FlowCInput input =  new FlowCInputBuilder(mandatoryflowBOutput)
                .setOptionalflowAOutput(optionalflowAOutput)
                .build();

我没有为Builder模式使用静态内部类。

欢迎任何建议。

1 个答案:

答案 0 :(得分:3)

你应该使用静态内部类。使用这种方法的关键是,内部可以直接访问正在构造的对象的私有属性。这有助于消除重复的代码,因为构建器不需要为构造维护一长串的临时状态。因此,您的代码可以像这样重写:

public class FlowCInput {
    private int output1FromB; // suppose that it is int
    private String output2FromA; // suppose that it is String
    private FlowCInput() { }
    //...

    public static class FlowCInputBuilder implements Builder<FlowCInput> {
        private final FlowCInput result;

        public FlowCInputBuilder(FlowBOutput mandatoryflowBOutput) {
            result = new FlowCInput();
            // output1FromB is private but still accessed from here
            result.output1FromB = mandatoryflowBOutput.getOutput1FromB();
        }

        public FlowCInputBuilder setOptionalflowAOutput(FlowAOutput optionalflowAOutput) {
            // same for output2FromA
            result.output2FromA = optionalflowAOutput.getOutput2FromA();
            return this;
        }

        @Override
        public FlowCInput build() {
            return result;
        }
    }
}

如您所见,构建器现在只包含FlowCInput个对象,它不会像以前那样不必要地保留mandatoryflowBOutputoptionalflowAOutput