lundi 19 octobre 2015

Builder pattern: nested objects created through other builders

Let's assume I have two objects, both created through the builder pattern and one is nested into other:

class Parent {
    private final Child child;

    private Parent(Child child) {
         this.child = child;
    }

    public static class Builder {
         private Child child;         

         public Builder() {}

         public Builder child(Child child) {
             this.child = child;
             return this;
         }

         public Parent build() {
             return new Parent(child);
         }
    }
}

class Child {
    private final long id;

    private Child(Builder builder) {
         this.id = builder.id;
    }

    public static class Builder {
         private long id;         

         public Builder() {}

         public Builder id(long id) {
             this.id = id;
             return this;
         }

         public Parent build() {
             return new Child(this);
         }
    }
}

So, the obvious usage is quite simple:

Person.Builder parentBuilder = new Person.Builder().child(new Child.Builder().id(10).build());

Is it quite common to make

public static class Builder {
     private ChildBuilder child;         

     public Builder() {}

     public Builder child(ChildBuilder child) {
         this.child = child;
         return this;
     }

     public Builder resetChildId() {
          child.id(0);
          return this;
     }

     public Parent build() {
         Child childToPass = child.build();
         return new Parent(childToPass);
     }
}

That way it is still possible to update the child#id later, however due to late binding the errors are thrown lately during Parent.Builder#build() method.

Aucun commentaire:

Enregistrer un commentaire