子类化Java Builder类


133

这篇多布斯博士文章,特别是Builder模式,我们如何处理将Builder子类化的情况?以该示例的简化版本为例,在该示例中我们想使用子类来添加GMO标签,一个简单的实现将是:

public class NutritionFacts {                                                                                                    

    private final int calories;                                                                                                  

    public static class Builder {                                                                                                
        private int calories = 0;                                                                                                

        public Builder() {}                                                                                                      

        public Builder calories(int val) { calories = val; return this; }                                                                                                                        

        public NutritionFacts build() { return new NutritionFacts(this); }                                                       
    }                                                                                                                            

    protected NutritionFacts(Builder builder) {                                                                                  
        calories = builder.calories;                                                                                             
    }                                                                                                                            
}

子类:

public class GMOFacts extends NutritionFacts {                                                                                   

    private final boolean hasGMO;                                                                                                

    public static class Builder extends NutritionFacts.Builder {                                                                 

        private boolean hasGMO = false;                                                                                          

        public Builder() {}                                                                                                      

        public Builder GMO(boolean val) { hasGMO = val; return this; }                                                           

        public GMOFacts build() { return new GMOFacts(this); }                                                                   
    }                                                                                                                            

    protected GMOFacts(Builder builder) {                                                                                        
        super(builder);                                                                                                          
        hasGMO = builder.hasGMO;                                                                                                 
    }                                                                                                                            
}

现在,我们可以编写如下代码:

GMOFacts.Builder b = new GMOFacts.Builder();
b.GMO(true).calories(100);

但是,如果我们弄错了订单,那么一切都会失败:

GMOFacts.Builder b = new GMOFacts.Builder();
b.calories(100).GMO(true);

问题当然是NutritionFacts.Builder返回NutritionFacts.Builder,而不是a GMOFacts.Builder,那么我们如何解决这个问题,还是有更好的Pattern来使用?

注意:这个类似问题的答案提供了我上面的课程;我的问题是有关确保构建器调用顺序正确的问题。


1
我想下面的链接描述了一个好办法:egalluzzo.blogspot.co.at/2010/06/...
Stuxnet病毒

1
但是,您build()的输出如何b.GMO(true).calories(100)
Sridhar Sarnobat '18 -4-4

Answers:


170

您可以使用泛型来解决它。我认为这称为“好奇地重复通用模式”

将基类构建器方法的返回类型设为通用参数。

public class NutritionFacts {

    private final int calories;

    public static class Builder<T extends Builder<T>> {

        private int calories = 0;

        public Builder() {}

        public T calories(int val) {
            calories = val;
            return (T) this;
        }

        public NutritionFacts build() { return new NutritionFacts(this); }
    }

    protected NutritionFacts(Builder<?> builder) {
        calories = builder.calories;
    }
}

现在使用派生的类构建器作为通用参数实例化基本构建器。

public class GMOFacts extends NutritionFacts {

    private final boolean hasGMO;

    public static class Builder extends NutritionFacts.Builder<Builder> {

        private boolean hasGMO = false;

        public Builder() {}

        public Builder GMO(boolean val) {
            hasGMO = val;
            return this;
        }

        public GMOFacts build() { return new GMOFacts(this); }
    }

    protected GMOFacts(Builder builder) {
        super(builder);
        hasGMO = builder.hasGMO;
    }
}

2
嗯,我想我必须要么(a)发表一个新问题,(b)用implements代替的重新设计extends,要么(c)丢弃所有内容。我现在有一个奇怪的编译错误,其中leafBuilder.leaf().leaf()leafBuilder.mid().leaf()还可以,但是leafBuilder.leaf().mid().leaf()失败了……
Ken YN

11
@gkamal return (T) this;unchecked or unsafe operations发出警告。这是不可避免的,对吧?
德米特里·明科夫斯基

5
要解决该unchecked cast警告,请参阅下面其他解决方案中建议的解决方案:stackoverflow.com/a/34741836/3114959
Stepan Vavra

8
请注意,这Builder<T extends Builder>实际上是原始类型 -应该为Builder<T extends Builder<T>>
蜘蛛鲍里斯(Boris)

2
@ user2957378的Builderfor GMOFacts也必须是通用的Builder<B extends Builder<B>> extends NutritionFacts.Builder<Builder>-并且该模式可以根据需要继续向下扩展。如果声明非通用生成器,则无法扩展模式。
蜘蛛鲍里斯(Boris)

44

仅作记录,以摆脱

unchecked or unsafe operations 警告

对于return (T) this;@dimadima和@Thomas N.所谈论的声明,以下解决方案在某些情况下适用。

使abstract生成器声明通用类型(T extends Builder在这种情况下)并声明protected abstract T getThis()抽象方法,如下所示:

public abstract static class Builder<T extends Builder<T>> {

    private int calories = 0;

    public Builder() {}

    /** The solution for the unchecked cast warning. */
    public abstract T getThis();

    public T calories(int val) {
        calories = val;

        // no cast needed
        return getThis();
    }

    public NutritionFacts build() { return new NutritionFacts(this); }
}

有关更多详细信息,请参见http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ205


为什么该build()方法在这里返回NutrutionFacts?
mvd

@mvd因为这是问题的答案?在子类型中,您将覆盖它,例如public GMOFacts build() { return new GMOFacts(this); }
Stepan Vavra

当我们想添加第二个孩子BuilderC extends BuilderB而不是第二个孩子BuilderB extends BuilderA时,BuilderB就会发生问题abstract
sosite

1
这不是问题的答案,因为基类可能不是抽象的!
罗兰

“使声明通用类型的构建器抽象”-如果我想直接使用该构建器怎么办?
雏菊

21

基于博客文章,此方法要求所有非叶子类都是抽象的,并且所有叶子类都必须是最终的。

public abstract class TopLevel {
    protected int foo;
    protected TopLevel() {
    }
    protected static abstract class Builder
        <T extends TopLevel, B extends Builder<T, B>> {
        protected T object;
        protected B thisObject;
        protected abstract T createObject();
        protected abstract B thisObject();
        public Builder() {
            object = createObject();
            thisObject = thisObject();
        }
        public B foo(int foo) {
            object.foo = foo;
            return thisObject;
        }
        public T build() {
            return object;
        }
    }
}

然后,您将拥有一些扩展该类及其构建器的中间类,并根据需要进行更多扩展:

public abstract class SecondLevel extends TopLevel {
    protected int bar;
    protected static abstract class Builder
        <T extends SecondLevel, B extends Builder<T, B>> extends TopLevel.Builder<T, B> {
        public B bar(int bar) {
            object.bar = bar;
            return thisObject;
        }
    }
}

最后,一个具体的叶子类可以按任何顺序在其任何父对象上调用所有构建器方法:

public final class LeafClass extends SecondLevel {
    private int baz;
    public static final class Builder extends SecondLevel.Builder<LeafClass,Builder> {
        protected LeafClass createObject() {
            return new LeafClass();
        }
        protected Builder thisObject() {
            return this;
        }
        public Builder baz(int baz) {
            object.baz = baz;
            return thisObject;
        }
    }
}

然后,您可以从层次结构中的任何类以任何顺序调用方法:

public class Demo {
    LeafClass leaf = new LeafClass.Builder().baz(2).foo(1).bar(3).build();
}

您知道为什么叶子类需要最终的吗?我希望我的具体类是可子类化的,但是还没有找到一种使编译器了解的类型的方法B,它总是被证明是基类。
大卫·甘斯特

请注意,LeafClass中的Builder类如何不遵循<T extends SomeClass, B extends SomeClass.Builder<T,B>> extends SomeClassParent.Builder<T,B>中介SecondLevel类所遵循的模式,而是声明特定的类型。在使用特定类型到达叶子之前,您不能实例化一个类,但是一旦完成,就无法进一步扩展它,因为您正在使用特定类型并且已经放弃了“好奇地重复使用的模板模式”。此链接可以帮助:angelikalanger.com/GenericsFAQ/FAQSections/...
Q23

7

您也可以覆盖该calories()方法,并让其返回扩展的构建器。编译是因为Java支持协变返回类型

public class GMOFacts extends NutritionFacts {
    private final boolean hasGMO;
    public static class Builder extends NutritionFacts.Builder {
        private boolean hasGMO = false;
        public Builder() {
        }
        public Builder GMO(boolean val)
        { hasGMO = val; return this; }
        public Builder calories(int val)
        { super.calories(val); return this; }
        public GMOFacts build() {
            return new GMOFacts(this);
        }
    }
    [...]
}

啊,我不知道,因为我来自C ++背景。对于这个小示例来说,这是一种有用的方法,但是对于一个成熟的类而言,重复所有方法将成为一种痛苦,并且容易出错。+1教我一些新知识!
Ken YN

在我看来,这并不能解决任何问题。对父级进行子分类的原因(IMO)是重用父级方法而不覆盖它们。如果这些类只是构建器方法中没有实际逻辑的值对象,除了设置简单值外,则在覆盖方法中调用父方法几乎没有值。
开发者Dude

答案解决了问题中描述的问题:使用构建器的代码以两种顺序编译。由于一种方法可以编译,而另一种则不能,因此我想毕竟必须有一些价值。
Flavio

3

还有另一种根据Builder模式创建类的方式,该方式符合“在继承中优先考虑组成”。

定义一个接口,该父类Builder将继承:

public interface FactsBuilder<T> {

    public T calories(int val);
}

的实现NutritionFacts几乎相同(除了Builder实现“ FactsBuilder”接口之外):

public class NutritionFacts {

    private final int calories;

    public static class Builder implements FactsBuilder<Builder> {
        private int calories = 0;

        public Builder() {
        }

        @Override
        public Builder calories(int val) {
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    protected NutritionFacts(Builder builder) {
        calories = builder.calories;
    }
}

Builder子类应扩展同一接口(除了不同的通用实现):

public static class Builder implements FactsBuilder<Builder> {
    NutritionFacts.Builder baseBuilder;

    private boolean hasGMO = false;

    public Builder() {
        baseBuilder = new NutritionFacts.Builder();
    }

    public Builder GMO(boolean val) {
        hasGMO = val;
        return this;
    }

    public GMOFacts build() {
        return new GMOFacts(this);
    }

    @Override
    public Builder calories(int val) {
        baseBuilder.calories(val);
        return this;
    }
}

请注意,这NutritionFacts.Builder是其中的一个字段GMOFacts.Builder(称为baseBuilder)。从FactsBuilder接口调用baseBuilder的同名方法实现的方法:

@Override
public Builder calories(int val) {
    baseBuilder.calories(val);
    return this;
}

的构造函数也发生了很大变化GMOFacts(Builder builder)。构造函数中对父类构造函数的第一次调用应传递适当的值NutritionFacts.Builder

protected GMOFacts(Builder builder) {
    super(builder.baseBuilder);
    hasGMO = builder.hasGMO;
}

GMOFacts类的完整实现:

public class GMOFacts extends NutritionFacts {

    private final boolean hasGMO;

    public static class Builder implements FactsBuilder<Builder> {
        NutritionFacts.Builder baseBuilder;

        private boolean hasGMO = false;

        public Builder() {
        }

        public Builder GMO(boolean val) {
            hasGMO = val;
            return this;
        }

        public GMOFacts build() {
            return new GMOFacts(this);
        }

        @Override
        public Builder calories(int val) {
            baseBuilder.calories(val);
            return this;
        }
    }

    protected GMOFacts(Builder builder) {
        super(builder.baseBuilder);
        hasGMO = builder.hasGMO;
    }
}

3

一个完整的3级多重生成器继承的示例如下所示

(有关带有构建器副本构造器的版本,请参见下面的第二个示例)

第一级-父级(可能是抽象的)

import lombok.ToString;

@ToString
@SuppressWarnings("unchecked")
public abstract class Class1 {
    protected int f1;

    public static class Builder<C extends Class1, B extends Builder<C, B>> {
        C obj;

        protected Builder(C constructedObj) {
            this.obj = constructedObj;
        }

        B f1(int f1) {
            obj.f1 = f1;
            return (B)this;
        }

        C build() {
            return obj;
        }
    }
}

第二级

import lombok.ToString;

@ToString(callSuper=true)
@SuppressWarnings("unchecked")
public class Class2 extends Class1 {
    protected int f2;

    public static class Builder<C extends Class2, B extends Builder<C, B>> extends Class1.Builder<C, B> {
        public Builder() {
            this((C) new Class2());
        }

        protected Builder(C obj) {
            super(obj);
        }

        B f2(int f2) {
            obj.f2 = f2;
            return (B)this;
        }
    }
}

第三级

import lombok.ToString;

@ToString(callSuper=true)
@SuppressWarnings("unchecked")
public class Class3 extends Class2 {
    protected int f3;

    public static class Builder<C extends Class3, B extends Builder<C, B>> extends Class2.Builder<C, B> {
        public Builder() {
            this((C) new Class3());
        }

        protected Builder(C obj) {
            super(obj);
        }

        B f3(int f3) {
            obj.f3 = f3;
            return (B)this;
        }
    }
}

以及用法示例

public class Test {
    public static void main(String[] args) {
        Class2 b1 = new Class2.Builder<>().f1(1).f2(2).build();
        System.out.println(b1);
        Class2 b2 = new Class2.Builder<>().f2(2).f1(1).build();
        System.out.println(b2);

        Class3 c1 = new Class3.Builder<>().f1(1).f2(2).f3(3).build();
        System.out.println(c1);
        Class3 c2 = new Class3.Builder<>().f3(3).f1(1).f2(2).build();
        System.out.println(c2);
        Class3 c3 = new Class3.Builder<>().f3(3).f2(2).f1(1).build();
        System.out.println(c3);
        Class3 c4 = new Class3.Builder<>().f2(2).f3(3).f1(1).build();
        System.out.println(c4);
    }
}


更长的版本为构建器提供了副本构造器:

第一级-父级(可能是抽象的)

import lombok.ToString;

@ToString
@SuppressWarnings("unchecked")
public abstract class Class1 {
    protected int f1;

    public static class Builder<C extends Class1, B extends Builder<C, B>> {
        C obj;

        protected void setObj(C obj) {
            this.obj = obj;
        }

        protected void copy(C obj) {
            this.f1(obj.f1);
        }

        B f1(int f1) {
            obj.f1 = f1;
            return (B)this;
        }

        C build() {
            return obj;
        }
    }
}

第二级

import lombok.ToString;

@ToString(callSuper=true)
@SuppressWarnings("unchecked")
public class Class2 extends Class1 {
    protected int f2;

    public static class Builder<C extends Class2, B extends Builder<C, B>> extends Class1.Builder<C, B> {
        public Builder() {
            setObj((C) new Class2());
        }

        public Builder(C obj) {
            this();
            copy(obj);
        }

        @Override
        protected void copy(C obj) {
            super.copy(obj);
            this.f2(obj.f2);
        }

        B f2(int f2) {
            obj.f2 = f2;
            return (B)this;
        }
    }
}

第三级

import lombok.ToString;

@ToString(callSuper=true)
@SuppressWarnings("unchecked")
public class Class3 extends Class2 {
    protected int f3;

    public static class Builder<C extends Class3, B extends Builder<C, B>> extends Class2.Builder<C, B> {
        public Builder() {
            setObj((C) new Class3());
        }

        public Builder(C obj) {
            this();
            copy(obj);
        }

        @Override
        protected void copy(C obj) {
            super.copy(obj);
            this.f3(obj.f3);
        }

        B f3(int f3) {
            obj.f3 = f3;
            return (B)this;
        }
    }
}

以及用法示例

public class Test {
    public static void main(String[] args) {
        Class3 c4 = new Class3.Builder<>().f2(2).f3(3).f1(1).build();
        System.out.println(c4);

        // Class3 builder copy
        Class3 c42 = new Class3.Builder<>(c4).f2(12).build();
        System.out.println(c42);
        Class3 c43 = new Class3.Builder<>(c42).f2(22).f1(11).build();
        System.out.println(c43);
        Class3 c44 = new Class3.Builder<>(c43).f3(13).f1(21).build();
        System.out.println(c44);
    }
}

2

如果您不想一眼或三角尖地盯着别人看,或者也许您不觉得自己...嗯...我的意思是... 咳嗽 ...您团队中的其他成员很快就会好奇地理解重复泛型模式,您可以执行以下操作:

public class TestInheritanceBuilder {
  public static void main(String[] args) {
    SubType.Builder builder = new SubType.Builder();
    builder.withFoo("FOO").withBar("BAR").withBaz("BAZ");
    SubType st = builder.build();
    System.out.println(st.toString());
    builder.withFoo("BOOM!").withBar("not getting here").withBaz("or here");
  }
}

由...支持

public class SubType extends ParentType {
  String baz;
  protected SubType() {}

  public static class Builder extends ParentType.Builder {
    private SubType object = new SubType();

    public Builder withBaz(String baz) {
      getObject().baz = baz;
      return this;
    }

    public Builder withBar(String bar) {
      super.withBar(bar);
      return this;
    }

    public Builder withFoo(String foo) {
      super.withFoo(foo);
      return this;
    }

    public SubType build() {
      // or clone or copy constructor if you want to stamp out multiple instances...
      SubType tmp = getObject();
      setObject(new SubType());
      return tmp;
    }

    protected SubType getObject() {
      return object;
    }

    private void setObject(SubType object) {
      this.object = object;
    }
  }

  public String toString() {
    return "SubType2{" +
        "baz='" + baz + '\'' +
        "} " + super.toString();
  }
}

和父类型:

public class ParentType {
  String foo;
  String bar;

  protected ParentType() {}

  public static class Builder {
    private ParentType object = new ParentType();

    public ParentType object() {
      return getObject();
    }

    public Builder withFoo(String foo) {
      if (!"foo".equalsIgnoreCase(foo)) throw new IllegalArgumentException();
      getObject().foo = foo;
      return this;
    }

    public Builder withBar(String bar) {
      getObject().bar = bar;
      return this;
    }

    protected ParentType getObject() {
      return object;
    }

    private void setObject(ParentType object) {
      this.object = object;
    }

    public ParentType build() {
      // or clone or copy constructor if you want to stamp out multiple instances...
      ParentType tmp = getObject();
      setObject(new ParentType());
      return tmp;
    }
  }

  public String toString() {
    return "ParentType2{" +
        "foo='" + foo + '\'' +
        ", bar='" + bar + '\'' +
        '}';
  }
}

关键点:

  • 将对象封装在构建器中,以便继承阻止您在父类型中保存的对象上设置字段
  • 调用super确保添加到超类型构建器方法中的逻辑(如果有的话)保留在子类型中。
  • 不利的一面是在父类中创建了虚假的对象...但是请参见下文,以解决此问题。
  • 优点一目了然,而且没有冗长的构造函数传递属性。
  • 如果您有多个线程访问您的构建器对象,我想我很高兴我不是您:)。

编辑:

我找到了一种解决伪造对象的方法。首先将此添加到每个构建器:

private Class whoAmI() {
  return new Object(){}.getClass().getEnclosingMethod().getDeclaringClass();
}

然后在每个构建器的构造器中:

  if (whoAmI() == this.getClass()) {
    this.obj = new ObjectToBuild();
  }

成本是new Object(){}匿名内部类的额外类文件


1

您可以做的一件事是在每个类中创建一个静态工厂方法:

NutritionFacts.newBuilder()
GMOFacts.newBuilder()

然后,此静态工厂方法将返回适当的生成器。您可以GMOFacts.Builder扩展一个NutritionFacts.Builder,这不是问题。这里的问题将是处理可见性...


0

以下IEEE贡献的Java中的精制Fluent Builder提供了对该问题的全面解决方案。

它将原始问题分解为继承不足准不变性两个子问题,并展示了这两个子问题的解决方案如何在Java中的经典构建器模式中通过代码重用而为继承支持打开。


该答案不包含任何有用的信息,至少不包含链接中给出的答案的摘要,并会导致需要登录的链接。
奏鸣曲

该答案链接到具有官方发布机构以及官方发布和共享程序的经过同行评审的会议出版物。
mc00x1

0

我创建了一个父类,抽象的通用生成器类,该类接受两个形式类型参数。第一个是针对由build()返回的对象的类型,第二个是针对每个可选参数设置器返回的类型。以下是用于说明目的的父类和子类:

// **Parent**
public abstract static class Builder<T, U extends Builder<T, U>> {
    // Required parameters
    private final String name;

    // Optional parameters
    private List<String> outputFields = null;


    public Builder(String pName) {
        name = pName;
    }

    public U outputFields(List<String> pOutFlds) {
        outputFields = new ArrayList<>(pOutFlds);
        return getThis();
    }


    /**
     * This helps avoid "unchecked warning", which would forces to cast to "T" in each of the optional
     * parameter setters..
     * @return
     */
    abstract U getThis();

    public abstract T build();



    /*
     * Getters
     */
    public String getName() {
        return name;
    }
}

 // **Child**
 public static class Builder extends AbstractRule.Builder<ContextAugmentingRule, ContextAugmentingRule.Builder> {
    // Required parameters
    private final Map<String, Object> nameValuePairsToAdd;

    // Optional parameters
    private String fooBar;


    Builder(String pName, Map<String, String> pNameValPairs) {
        super(pName);
        /**
         * Must do this, in case client code (I.e. JavaScript) is re-using
         * the passed in for multiple purposes. Doing {@link Collections#unmodifiableMap(Map)}
         * won't caught it, because the backing Map passed by client prior to wrapping in
         * unmodifiable Map can still be modified.
         */
        nameValuePairsToAdd = new HashMap<>(pNameValPairs);
    }

    public Builder fooBar(String pStr) {
        fooBar = pStr;
        return this;
    }


    @Override
    public ContextAugmentingRule build() {
        try {
            Rule r = new ContextAugmentingRule(this);
            storeInRuleByNameCache(r);
            return (ContextAugmentingRule) r;
        } catch (RuleException e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    Builder getThis() {
        return this;
    }
}

这个满足了我的需求。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.