Peter
Peter

Reputation: 857

When is the Builder pattern preferable to inheritance and multiple implementations?

When does it make sense to use a builder pattern like:

private static final Foo FOO1 = Foo.Builder().setX(...).setY(...).setZ(...).build();
private static final Foo FOO2 = Foo.Builder().setX(...).setY(...).setZ(...).build();
private static final Foo FOO3 = Foo.Builder().setX(...).setY(...).setZ(...).build();
... x100 ...

VS something like

public class MyFoos {
  public static class Foo1 implements Foo {
    public String getX() {...}
    public String getY() {...}
    public String getZ() {...}
  }

  public static class Foo2 implements Foo {
    public String getX() {...}
    public String getY() {...}
    public String getZ() {...}
  }

  public static class Foo3 implements Foo {
    public String getX() {...}
    public String getY() {...}
    public String getZ() {...}
  }
  ... x100...
}

Does it matter how complex Foo is? For example, let's say if we used a Foo.Builder(), we might need to call something like:

Foo.Builder().setSpecialFunction(new Function() {...})

where Function is something like http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html

does that suggest that the Builder pattern is not appropriate in this situation? If not, what would be preferable? Thanks!

Upvotes: 0

Views: 234

Answers (1)

korifey
korifey

Reputation: 3509

The second design choise is terrible - do not abuse inheritance. Builder pattern (according to Bloch's "Effective Java") is appropriate to use when number of parameters in constructors is more than some constant (say 4, according to Bloch).

Upvotes: 1

Related Questions