【问题标题】:Builder pattern for polymorphic object hierarchy: possible with Java?多态对象层次结构的构建器模式:Java 可能吗?
【发布时间】:2012-02-04 02:57:40
【问题描述】:

我有一个接口层次结构,Child 实现了Parent。我想使用不可变对象,所以我想设计Builder 方便地构造这些对象的类。但是,我有很多Child接口,我不想在每种类型的子构建器中重复构建Parents的代码。

因此,假设以下定义:

public interface Parent {
    public Long getParentProperty();
}

public interface Child1 extends Parent {
    public Integer getChild1Property(); 
}

public interface Child2 extends Parent {
    public String getChild2PropertyA();
    public Object getChild2PropertyB();
}

如何有效地实现构建器Child1BuilderChild2Builder?他们应该支持这样的操作:

Child1 child1 = Child1Builder.newChild1().withChild1Property(5).withParentProperty(10L);

Child2 child2 = Child2Builder.newChild2().withChild2PropertyA("Hello").withParentProperty(10L).withChild2PropertyB(new Object());

我不想为每个子构建器实现withParentProperty 的特殊情况。

编辑添加第二个属性到Child2 以澄清这不能用简单的泛型来完成。我不是在寻找一种结合Child1Child2 的方法——我在寻找一种方法来实现Builder 系统,它不会重复为每个子类构建父类的工作。

感谢您的帮助!

【问题讨论】:

  • 如果 Child1 和 Child2 的实现继承自同样实现 Parent 的同一个实现,那么您可以拥有一个具有方法 withParentProperty() 的父 Builder
  • 但是父 Builder 将返回 Parent 引用,而不是适当的 Child 引用,对吧?
  • 一旦你尝试实现,你会发现它比这更复杂,你需要下面提供的类似 seh 的东西。如果你能演示一个更简单的实现,我很乐意看到它!

标签: java design-patterns builder


【解决方案1】:

我想象的解决方案类似于Curiously Recurring Template Pattern,或CRTP。您可以定义一个基类来处理与父相关的初始化,但您仍然会发现 getParent()getThis() 两个样板方法在每个派生的与子相关的构建器类中重复太多。

看看:

abstract class ParentBase implements Parent
{
  @Override
  public final Long getParentProperty()
  {
      return parentProperty_;
  }


  protected void setParentProperty(Long value)
  {
      parentProperty_ = value;
  }


  private Long parentProperty_;
}


abstract class ParentBuilder<T extends ParentBuilder<T>>
{
  T withParentProperty(Long value)
  {
      getParent().setParentProperty(value);
      return getThis();
  }


  protected abstract ParentBase getParent();


  protected abstract T getThis();
}


final class ConcreteChild1 extends ParentBase implements Child1
{
  @Override
  public Integer getChild1Property()
  {
      return childProperty_;
  }


  public void setChild1Property(Integer value)
  {
      childProperty_ = value;
  }


  private Integer childProperty_;
}


final class Child1Builder extends ParentBuilder<Child1Builder>
{
  public Child1Builder()
  {
     pending_ = new ConcreteChild1();
  }


  public Child1Builder withChild1Property(Integer value)
  {
      pending_.setChild1Property(value);
      return this;
  }


  @Override
  protected ParentBase getParent()
  {
      return pending_;
  }


  @Override
  protected Child1Builder getThis()
  {
      return this;
  }


  private final ConcreteChild1 pending_;
}

如您所见,ParentBuilder 类型期望与派生类型合作,以允许它返回正确类型的实例。它自己的this 引用不会到期,因为ParentBuilder 中的this 类型当然是ParentBuilder,而不是Child1Builder,因为它旨在维护“流畅”的调用链。

我把“getThis() 把戏”归功于Angelika Langer's tutorial entry

【讨论】:

  • 啊哈哈,getThis() 技巧是我错过的步骤!我不介意额外的样板 - 我只是想避免为以后添加到父级的每个字段复制(和维护!)代码。感谢您的回答。
  • Java.net 上有一篇关于类似解决方案的精彩博文:weblogs.java.net/blog/emcmanus/archive/2010/10/25/…
  • 如果您想添加 Child1 的具体子类的另一个嵌套,例如Child2 和 Child2Builder 如何声明 Child2Builder 和 Child1Builders getThis 方法?
  • 想到两件事:ConcreteChild1Child1Builder 都不能是最终的,Child1Builder 需要一个类型参数来指示它构建的具体类型,然后可以是 @ 987654338@ 或您提议的ConcreteChild2。由于 Java 缺少类型参数的默认值,因此直接使用类 Child1Builder 会更烦人。引入Child1BuilderChild2Builder 都可以扩展的中间抽象参数化类可能会有所帮助。
  • @seh 感谢您的洞察力。这个介入的抽象类会提供什么? getThis()?似乎这需要来自可实例化的构建器类而不是抽象类。它只是用于类的类型参数吗?即class Child1Builder extends ParentBuilder&lt;AbstractChildBuilder&gt;
【解决方案2】:

我不认为getParent()getThis() 是必要的,如果你愿意接受withXXXProperty() 方法从“最年轻”调用到“最老”的限制:

class Parent
{
    private final long parentProperty;

    public long getParentProperty()
    {
        return parentProperty;
    }

    public static abstract class Builder<T extends Parent>
    {
        private long parentProperty;

        public Builder<T> withParentProperty( long parentProperty )
        {
            this.parentProperty = parentProperty;
            return this;
        }

        public abstract T build();
    }

    public static Builder<?> builder()
    {
        return new Builder<Parent>()
        {
            @Override
            public Parent build()
            {
                return new Parent(this);
            }
        };
    }

    protected Parent( Builder<?> builder )
    {
        this.parentProperty = builder.parentProperty;
    }
}

class Child1 extends Parent
{
    private final int child1Property;

    public int getChild1Property()
    {
        return child1Property;
    }

    public static abstract class Builder<T extends Child1> extends Parent.Builder<T>
    {
        private int child1Property;

        public Builder<T> withChild1Property( int child1Property )
        {
            this.child1Property = child1Property;
            return this;
        }

        public abstract T build();
    }

    public static Builder<?> builder()
    {
        return new Builder<Child1>()
        {
            @Override
            public Child1 build()
            {
                return new Child1(this);
            }
        };
    }

    protected Child1( Builder<?> builder )
    {
        super(builder);
        this.child1Property = builder.child1Property;
    }

}

class Child2 extends Parent
{

    private final String child2PropertyA;
    private final Object child2PropertyB;

    public String getChild2PropertyA()
    {
        return child2PropertyA;
    }

    public Object getChild2PropertyB()
    {
        return child2PropertyB;
    }

    public static abstract class Builder<T extends Child2> extends Parent.Builder<T>
    {
        private String child2PropertyA;
        private Object child2PropertyB;

        public Builder<T> withChild2PropertyA( String child2PropertyA )
        {
            this.child2PropertyA = child2PropertyA;
            return this;
        }

        public Builder<T> withChild2PropertyB( Object child2PropertyB )
        {
            this.child2PropertyB = child2PropertyB;
            return this;
        }
    }

    public static Builder<?> builder()
    {
        return new Builder<Child2>()
        {
            @Override
            public Child2 build()
            {
                return new Child2(this);
            }
        };
    }

    protected Child2( Builder<?> builder )
    {
        super(builder);
        this.child2PropertyA = builder.child2PropertyA;
        this.child2PropertyB = builder.child2PropertyB;
    }
}

class BuilderTest
{
    public static void main( String[] args )
    {
        Child1 child1 = Child1.builder()
                .withChild1Property(-3)
                .withParentProperty(5L)
                .build();

        Child2 grandchild = Child2.builder()
                .withChild2PropertyA("hello")
                .withChild2PropertyB(new Object())
                .withParentProperty(10L)
                .build();
    }
}

这里还有一些样板:每个builder() 方法中的匿名具体Builder,以及每个构造函数中的super() 调用。 (注意:假设每个级别都是为了进一步的可继承性而设计的。如果在任何时候你有一个final 后代,你可以将构建器类设为具体,并将构造器设为私有。)

但是我认为这个版本更容易理解,对于下一个出现并且必须维护你的代码的程序员(没有自引用泛型,对于初学者;Builder&lt;X&gt; 构建Xs)。恕我直言,要求在父属性之前在构建器上设置子属性在一致性方面是一个优势,但在灵活性方面是一个劣势。

【讨论】:

  • 这些都是好点,大卫。当我要求我能够以任何顺序调用setPropertyX 方法时,我可能有点迂腐。接受的答案肯定很难阅读。
【解决方案3】:

这是一个使用泛型的解决方案。

public abstract class ParentBuilder<T extends ParentBuilder<T>> {
    private long parentProperty;

    protected abstract T self();

    public T withParentProperty(long parentProperty) {
        this.parentProperty = parentProperty;
        return self();
    }

    protected static class SimpleParent implements Parent {
        private long parentProperty;

        public SimpleParent(ParentBuilder<?> builder) {
            this.parentProperty = builder.parentProperty;
        }

        @Override
        public Long getParentProperty() {
            return parentProperty;
        }
    }
}
public final class Child1Builder extends ParentBuilder<Child1Builder> {
    private int child1Property;

    private Child1Builder() {}

    public static Child1Builder newChild1() {
        return new Child1Builder();
    }

    @Override
    protected Child1Builder self() {
        return this;
    }

    public Child1Builder withChild1Property(int child1Property) {
        this.child1Property = child1Property;
        return self();
    }

    public Child1 build() {
        return new SimpleChild1(this);
    }

    private final class SimpleChild1 extends SimpleParent implements Child1 {
        private int child1Property;

        public SimpleChild1(Child1Builder builder) {
            super(builder);
            this.child1Property = builder.child1Property;
        }

        @Override
        public Integer getChild1Property() {
            return child1Property;
        }
    }
}
public final class Child2Builder extends ParentBuilder<Child2Builder> {

    private String child2propertyA;
    private Object child2propertyB;

    private Child2Builder() {}

    public static Child2Builder newChild2() {
        return new Child2Builder();
    }

    @Override
    protected Child2Builder self() {
        return this;
    }

    public Child2Builder withChild2PropertyA(String child2propertyA) {
        this.child2propertyA = child2propertyA;
        return self();
    }

    public Child2Builder withChild2PropertyB(Object child2propertyB) {
        this.child2propertyB = child2propertyB;
        return self();
    }

    public Child2 build() {
        return new SimpleChild2(this);
    }

    private static final class SimpleChild2 extends SimpleParent implements Child2 {
        private String child2propertyA;
        private Object child2propertyB;

        public SimpleChild2(Child2Builder builder) {
            super(builder);
            this.child2propertyA = builder.child2propertyA;
            this.child2propertyB = builder.child2propertyB;
        }

        @Override
        public String getChild2PropertyA() {
            return child2propertyA;
        }

        @Override
        public Object getChild2PropertyB() {
            return child2propertyB;
        }
    }
}

对于较大的层次结构或具体类不只是在叶子上的层次结构,有必要将上述具体构建器的一部分提取到中间抽象类中。例如,Child1Builder 可以分为以下两个类Child1BuilderAbstractChild1Builder,后者可以由另一个子构建器扩展。

public abstract class AbstractChild1Builder<T extends AbstractChild1Builder<T>> extends ParentBuilder<T> {

    protected int child1Property;

    public T withChild1Property(int child1Property) {
        this.child1Property = child1Property;
        return self();
    }

    protected final class SimpleChild1 extends SimpleParent implements Child1 {
        private int child1Property;

        public SimpleChild1(AbstractChild1Builder<Child1Builder> builder) {
            super(builder);
            this.child1Property = builder.child1Property;
        }

        @Override
        public Integer getChild1Property() {
            return child1Property;
        }
    }
}
public final class Child1Builder extends AbstractChild1Builder<Child1Builder> {
    private Child1Builder() {}

    public static AbstractChild1Builder<Child1Builder> newChild1() {
        return new Child1Builder();
    }

    @Override
    protected Child1Builder self() {
        return this;
    }

    public Child1 build() {
        return new SimpleChild1(this);
    }   
}

【讨论】:

  • 感谢您展示了如何通过将 Builder 类拆分为 2 类来将模式扩展到多代对象。正是我想要的。
【解决方案4】:

没有建设者可能会这样?:

interface P {
    public Long getParentProperty();
}
interface C1 extends P {
    public Integer getChild1Property();
}
interface C2 extends P {
    public String getChild2PropertyA();
    public Object getChild2PropertyB();
}
abstract class PABC implements P {
    @Override public final Long getParentProperty() {
        return parentLong;
    }
    protected Long parentLong;
    protected PABC setParentProperty(Long value) {
        parentLong = value;
        return this;
    }
}
final class C1Impl extends PABC implements C1 {
    protected C1Impl setParentProperty(Long value) {
        super.setParentProperty(value);
        return this;
    }
    @Override public Integer getChild1Property() {
        return n;
    }
    public C1Impl setChild1Property(Integer value) {
        n = value;
        return this;
    }
    private Integer n;
}
final class C2Impl extends PABC implements C2 {
    private String string;
    private Object object;

    protected C2Impl setParentProperty(Long value) {
        super.setParentProperty(value);
        return this;
    }
    @Override public String getChild2PropertyA() {
    return string;
    }

    @Override public Object getChild2PropertyB() {
        return object;
    }
    C2Impl setChild2PropertyA(String string) {
        this.string=string;
        return this;
    }
    C2Impl setChild2PropertyB(Object o) {
        this.object=o;
        return this;
    }
}
public class Myso9138027 {
    public static void main(String[] args) {
        C1Impl c1 = new C1Impl().setChild1Property(5).setParentProperty(10L);
        C2Impl c2 = new C2Impl().setChild2PropertyA("Hello").setParentProperty(10L).setChild2PropertyB(new Object());
    }
}

【讨论】:

  • 这是一个更简单的解决方案 - 感谢您的写作!它会产生可变对象,我试图避免这种情况,并且仍然需要我在每个子对象中实现setParentProperty(对于每个父属性!),所以我认为我可能需要更复杂的东西。
  • 使对象不可变将需要为每种类型的子对象设置两个类。那样可以么?你能忍受一个显式的 constrictor 而不是 set 属性链接吗?属性可以放在地图中吗? - 此外,在每个孩子中实现 setParentProperty 只需几行代码 - 在这种情况下,替代方案将是一个丑陋的沮丧
  • 如果这些类与构建器在同一个包中,seh 提供的替代方案只需要为每个孩子一个类(经过一些访问级别的调整),对吧? setParentProperty 在每个子节点中的实现只有几行代码,但是当我添加/删除父属性时,维护成本越来越高。有 5 个父属性和 8 个子类(我的实际情况),即 40 个额外的方法,因此建议的额外 getThis 和 getParent seh 相比之下非常轻量级。如果我需要添加父属性,则无需更改子属性。
  • 好的。考虑在父级和每个子级中使用两个映射:propertyNameToType 和 propertyNameToValue。轻松构建它们并将不可变映射粘贴到您向用户公开的类中。
  • 不,setter 可以检查新值的类型是否正确,因为我们有 propertyNameToType 映射。不过,使用 getter 需要强制转换。
【解决方案5】:

使用泛型,如下:

public interface Parent {
    public Long getParentProperty();
}

public interface Child<T> {
    public T getChildProperty(); 
}

然后用Child&lt;Integer&gt;代替Child1,用Child&lt;String&gt;代替Child2。

【讨论】:

  • 在这种简单的情况下,这将是实现 Child1 和 Child2 的好方法,但它并没有解决我的问题的中心焦点,即在没有重复代码的情况下有效地实现这些东西的构建器。这种方式的泛型不支持我原帖中的操作。
  • 我很确定他关于泛型的观点是您将大部分 Child 逻辑整合到一个类中,从而使定义父级构建逻辑一次变得微不足道。
  • 不,这只是一个例子。在实际场景中,我无法将我的大部分子逻辑合​​并到一个类中。我想要不同的类做不同的事情,但有一个共同的父类。
【解决方案6】:
package so9138027take2;
import java.util.*;
import so9138027take2.C2.Names;
interface P {
    public Object getParentProperty(Names name);
    enum Names {
        i(Integer.class), d(Double.class), s(String.class);
        Names(Class<?> clazz) {
            this.clazz = clazz;
        }
        final Class<?> clazz;
    }
}
interface C1 extends P {
    public Object getChildProperty(Names name);
    enum Names {
        a(Integer.class), b(Double.class), c(String.class);
        Names(Class<?> clazz) {
            this.clazz = clazz;
        }
        final Class<?> clazz;
    }
}
interface C2 extends P {
    public Object getChildProperty(Names name);
    enum Names {
        x(Integer.class), y(Double.class), z(String.class);
        Names(Class<?> clazz) {
            this.clazz = clazz;
        }
        final Class<?> clazz;
    }
}
abstract class PABCImmutable implements P {
    public PABCImmutable(PABC parent) {
        parentNameToValue = Collections.unmodifiableMap(parent.parentNameToValue);
    }
    @Override public final Object getParentProperty(Names name) {
        return parentNameToValue.get(name);
    }
    public String toString() {
        return parentNameToValue.toString();
    }
    final Map<Names, Object> parentNameToValue;
}
abstract class PABC implements P {
    @Override public final Object getParentProperty(Names name) {
        return parentNameToValue.get(name);
    }
    protected PABC setParentProperty(Names name, Object value) {
        if (name.clazz.isInstance(value)) parentNameToValue.put(name, value);
        else
            throw new RuntimeException("value is not valid for " + name);
        return this;
    }
    public String toString() {
        return parentNameToValue.toString();
    }
    EnumMap<Names, Object> parentNameToValue = new EnumMap<Names, Object>(P.Names.class);
}
final class C1Immutable extends PABCImmutable implements C1 {
    public C1Immutable(C1Impl c1) {
        super(c1);
        nameToValue =  Collections.unmodifiableMap(c1.nameToValue);
    }
    @Override public Object getChildProperty(C1.Names name) {
        return nameToValue.get(name);
    }
    public String toString() {
        return super.toString() + nameToValue.toString();
    }
    final Map<C1.Names, Object> nameToValue;
}
final class C1Impl extends PABC implements C1 {
    @Override public Object getChildProperty(C1.Names name) {
        return nameToValue.get(name);
    }
    public Object setChildProperty(C1.Names name, Object value) {
        if (name.clazz.isInstance(value)) nameToValue.put(name, value);
        else
            throw new RuntimeException("value is not valid for " + name);
        return this;
    }
    public String toString() {
        return super.toString() + nameToValue.toString();
    }
    EnumMap<C1.Names, Object> nameToValue = new EnumMap<C1.Names, Object>(C1.Names.class);
}
final class C2Immutable extends PABCImmutable implements C2 {
    public C2Immutable(C2Impl c2) {
        super(c2);
        this.nameToValue = Collections.unmodifiableMap(c2.nameToValue);
    }
    @Override public Object getChildProperty(C2.Names name) {
        return nameToValue.get(name);
    }
    public String toString() {
        return super.toString() + nameToValue.toString();
    }
    final Map<C2.Names, Object> nameToValue;
}
final class C2Impl extends PABC implements C2 {
    @Override public Object getChildProperty(C2.Names name) {
        return nameToValue.get(name);
    }
    public Object setChildProperty(C2.Names name, Object value) {
        if (name.clazz.isInstance(value)) {
            nameToValue.put(name, value);
        } else {
            System.out.println("name=" + name + ", value=" + value);
            throw new RuntimeException("value is not valid for " + name);
        }
        return this;
    }
    public String toString() {
        return super.toString() + nameToValue.toString();
    }
    EnumMap<C2.Names, Object> nameToValue = new EnumMap<C2.Names, Object>(C2.Names.class);
}
public class So9138027take2 {
    public static void main(String[] args) {
        Object[] parentValues = new Object[] { 1, 2., "foo" };
        C1Impl c1 = new C1Impl();
        Object[] c1Values = new Object[] { 3, 4., "bar" };
        for (P.Names name : P.Names.values())
            c1.setParentProperty(name, parentValues[name.ordinal()]);
        for (C1.Names name : C1.Names.values())
            c1.setChildProperty(name, c1Values[name.ordinal()]);
        C2Impl c2 = new C2Impl();
        Object[] c2Values = new Object[] { 5, 6., "baz" };
        for (P.Names name : P.Names.values())
            c2.setParentProperty(name, parentValues[name.ordinal()]);
        for (C2.Names name : C2.Names.values())
            c2.setChildProperty(name, c2Values[name.ordinal()]);
        C1 immutableC1 = new C1Immutable(c1);
        System.out.println("child 1: "+immutableC1);
        C2 immutableC2 = new C2Immutable(c2);
        System.out.println("child 2: "+immutableC2);
    }
}

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多