步骤生成器模式使用委托和枚举?

时间:2018-04-04 15:49:29

标签: java design-patterns enums builder delegation

我正在研究这个项目,基本上这就是我想要实现的目标。

这就是我所拥有的:

MyObject obj = MyObject.builder()
                       .withValue("string")
                       .withAnotherValue("string")
                       .build();

MyObject obj = MyObject.builder()
                       .withValue("string")
                       .withAnotherValue("string")
                       .withField("key", "value")
                       .build();

因此,步骤构建器模式会强制用户按此顺序使用withValue()方法和withAnotherValue()方法。方法field()是可选的,可以根据需要多次使用。我在此网站后面举例http://www.svlada.com/step-builder-pattern/

所以我想要实现的是:

MyObject obj = MyObject.builder(Type.ROCK)
                       .withColour("blue")
                       .withValue("string")
                       .withAnotherValue("string")
                       .build();

MyObject obj = MyObject.builder(Type.STONE)
                       .withWeight("heavy")
                       .withValue("string")
                       .withAnotherValue("string")
                       .withField("key", "value")
                       .build();

因此,在builder()方法中,您将放置一个枚举类型,并且基于枚举,您将看到一组不同的方法。因此,对于ROCK,withValue()withAnotherValue()withColour()现在是强制性的。但对于STONE withWeight()withAnotherValue()withColour()是强制性的。

我这样的事情可能吗?过去两天我一直在尝试解决这个问题,但我似乎无法让它为每种类型提供具体的方法。它只显示了Builder中的所有方法。

非常感谢任何想法和帮助。

代码:

枚举

public enum Type implements ParameterType<Type> {

  ROCK, STONE

}

参数类型

interface ParameterType<T> {}

为MyObject

public class MyObject implements Serializable {

  private static final long serialVersionUID = -4970453769180420689L;

  private List<Field> fields = new ArrayList<>();

  private MyObject() {
  }

  public interface Type {

    Value withValue(String value);
  }

  public interface Value {

    Build withAnotherValue(String anotherValue);
  }

  public interface Build {

    MyObject build();
  }

  public Type builder(Parameter type) {
    return new Builder();
  }

  public static class Builder implements Build, Type, Value {

    private final List<Field> fields = new ArrayList<>();

    @Override
    public Build withAnotherValue(String anotherValue) {
      fields.add(new Field("AnotherValue", anotherValue));
      return this;
    }

    @Override
    public Value withValue(String value) {
      fields.add(new Field("Value", value));
      return this;
    }

    @Override
    public MyObject build() {
      MyObject myObject = new MyObject();
      myObject.fields.addAll(this.fields);
      return myObject;
    }
  }

}

3 个答案:

答案 0 :(得分:1)

使用enum无法做到这一点,但您可以使用自定义enum来执行此操作 - 类似于:

public final class Type<B extends MyObject.Builder> {
    private final Supplier<? extends B> supplier;

    private Type(Supplier<? extends B> supplier) {
        this.supplier = Objects.requireNonNull(supplier);
    }

    public B builder() {
        return supplier.get();
    }

    public static final Type<MyObject.RockBuilder> ROCK =
        new Type<>(MyObject.RockBuilder::new);

    public static final Type<MyObject.StoneBuilder> STONE =
        new Type<>(MyObject.StoneBuilder::new);
}

public class MyObject {
    // ...

    // And this method is probably superfluous at this point.
    public static <B extends MyObject.Builder> builder(Type<? extends B> type) {
        return type.builder();
    }
}

您可以轻松地将该方法应用于步骤构建器,但这里有一个单独的问题。由于步骤构建器中的每个步骤都指定了返回类型中的下一步,因此您无法轻松地重复使用步骤接口。例如,您需要声明单独的接口RockValueStepStoneValueStep等,因为接口本身指定了步骤顺序。

唯一简单的方法是,如果单独的类型(岩石,石头等)仅严格添加步骤,例如Type.ROCK返回ColourStepType.STONE返回WeightStepColourStepWeightStep都返回ValueStep

// Rock builder starts here.
interface ColourStep { ValueStep withColour(String c); }
// Stone builder starts here.
interface WeightStep { ValueStep withWeight(String w); }
// Shared.
interface ValueStep { AnotherValueStep withValue(String v); }

然后:

public final class Type<B /* extends ABuilderStepMarker, possibly */> {
    // (Constructor and stuff basically same as before.)

    public static final Type<MyObject.ColourStep> ROCK =
        new Type<>(/* implementation */::new);

    public static final Type<MyObject.WeightStep> STONE =
        new Type<>(/* implementation */::new);
}

使用enum无法完成此类事情的原因非常多:

  • enum不能是通用的:

    // This is an error.
    enum Type<T> {
    }
    
  • 虽然您可以在enum上声明一个抽象方法并使用协变返回类型覆盖它,但协变返回类型永远不可见:

    // This is valid code, but the actual type of
    // Type.ROCK is just Type, so the return type of
    // Type.ROCK.builder() is just MyObject.Builder,
    // despite the override.
    enum Type {
        ROCK {
            @Override
            public MyObject.RockBuilder builder() {
                return new MyObject.RockBuilder();
            }
        };
        public abstract MyObject.Builder builder();
    }
    

答案 1 :(得分:0)

考虑到您正在为特定类型的构建器寻找特定方法,具有多个构建器,每种类型的MyObject可以构建一个可能最佳。您可以创建一个定义构建器的接口,然后将公共功能放入一个抽象类中,各个构建器将从该类中扩展。例如:

public interface Builder {
    public MyObject build();
}

public abstract class AbstractBuilder() {

    private final List<Field> fields = new ArrayList<>();

    protected void addField(String key, String value) {
        fields.add(new Field(key, value));
    }

    @Override
    public MyObject build() {
        MyObject myObject = new MyObject();
        myObject.fields.addAll(this.fields);
        return myObject;
    }
}

public class StoneBuilder extends AbstractBuilder {

    public StoneBuilder withValue(String value) {
        addField("Value", value);
        return this;
    }

    // ...More builder methods...
}

public class RockBuilder extends AbstractBuilder {

    public RockBuilder withAnotherValue(String value) {
        addField("AnotherValue", value);
        return this;
    }

    // ...More builder methods...
}

这允许您以下列方式构建MyObject个实例:

MyObject obj = new RockBuilder()
                   .withValue("string")
                   .build();

MyObject obj = new StoneBuilder()
                   .withAnotherValue("string")
                   .build();

答案 2 :(得分:0)

您的问题可以概括如下:“我如何编写以下方法?”

public <T extends AbstractBuilder> T builder(final SomeNonGenericObject object) {
    // code goes here
}

答案是:“你不能,因为编译器无法推断T的类型是什么。唯一可行的方法是以某种方式将T作为参数传递:

public <T extends AbstractBuilder> T builder(final SomeNonGenericObject object, final Class<T> builderClass) {
    // code goes here
}

public <T extends AbstractBuilder> T builder(final SomeGenericObject<T> object) {
    // code goes here
}

例如:

public <T extends AbstractBuilder> T builder(final Supplier<T> object) {
    return supplier.get();
}

final Supplier<AbstractBuilder> rockBuilderSupplier = RockBuilder::new;
builder(rockBuilerSupplier)
    .withColour("blue")
    // etc

或者只是简单地使用Justin Albano的答案,它的效果也一样。