Wednesday, August 10, 2016

Builder Pattern for Immutability

For immutability, we can use either Factory or Builder

If we have a lot parameters in the constructor, the code is kind of mess. And you may have 100 constructors because of this.

Builder pattern:
This is a combination of two constructs:

  • A static inner class that implements a generic builder interface
  • And a private constructor for the immutable class itself.

The static inner class is the builder for the immutable class, and it provides the only way that a developer can get hold of new instances of the immutable type.
One very common implementation is for the Builder class to have exactly the same fields as the immutable class, but to allow mutation of the fields.
This listing shows how you might use this to model a microblogging update (again, building on the earlier listings in this chapter).


public interface ObjBuilder {
 T build();
}


public class Update {

   //   Final fields must be initialized in constructor

 private final Author author;
 private final String updateText;

 private Update(Builder b_) {
  author = b_.author;
  updateText = b_.updateText;
 }

  // Builder class must be static inner

 public static class Builder implements ObjBuilder<Update> {
  private Author author;
  private String updateText;
  
  // Methods on Builder return Builder for chain calls

  public Builder author(Author author_) {
   author = author_;
   return this;
  }

  public Builder updateText(String updateText_) {
   updateText = updateText_;
   return this;
  }

  public Update build() {
   return new Update(this);
  }
   //hashCode() and equals() methods omitted
   
 }
}
class UpdateTest{
 public static void main(String[] args){
  Update.Builder ub = new Update.Builder();
  Author myAuthor = new Author();
  Update u = ub.author(myAuthor ).updateText("Hello").build();
 }
}



With this code, you could then create a new Update object like this:
 Update.Builder ub = new Update.Builder();
 Update u = ub.author(myAuthor).updateText("Hello").build();




















No comments:

Post a Comment