【发布时间】:2018-09-14 06:33:20
【问题描述】:
我正在从事这个项目,基本上这就是我想要实现的目标。
这就是我所拥有的:
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> {}
我的对象
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;
}
}
}
【问题讨论】:
标签: java design-patterns enums builder delegation