Adopting Builder Pattern with Abstract class

Builder Pattern helps simplify constructor and increase readability with fluent interface. It can also be handy to make the class immutable (not demonstrated here).
Here is an example if you have an abstract base class in the way:

The abstract base class:

public abstract class BaseClass {

private String name;

protected static abstract class BaseBuilder<T extends BaseClass, B extends BaseBuilder>{
  protected T actualClass;
  protected B actualClassBuilder;

  protected abstract T getActual();
  protected abstract B getActualBuilder();
  protected BaseBuilder() {
    actualClass = getActual();
    actualClassBuilder = getActualBuilder();
  }
  public B name(String name) {
    actualClass.setName(name); return actualClassBuilder;
  }
  public T build() { return actualClass; }
}

private void setName(String name) { this.name = name; }

private String getName() { return name; }

}

The concrete, extending class:

public class ConcreteClass extends BaseClass {
  public static class Builder extends BaseBuilder<ConcreteClass, Builder> { 

    public Builder anotherField(String anotherField) {
            actualClass.setAnotherField(anotherField);
            return this;
        }

        @Override
        protected ActionTask getTask() {
            return new ActionTask();
        }

        @Override
        protected Builder getBuilder() {
            return this;
        }
}

To use it:

ConcreteClass myConcreteObject =
  new ConcreteClass.Builder()
    .name("one")
    .anotherField("two")
    .build();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s