Builder Pattern

Builder Pattern is used to encapsulate the construction of a product and allow it to be constructed in steps.

Builder Pattern is an excellent design pattern when you are faced with many constructor parameters (more than 4). We have other options like having a constructor for each optional parameter or have a default constructor and rely on the Java Bean pattern, in which a setter and getter is provided for each attribute. But both of these options are ugly and error prone:

  • Multiple constructors is hard to read and open the possibility of passing the arguments in wrong order
  • Default constructor along with Java Bean pattern (getter & setter) suffers from below serious problems:
    • Object can be in an inconsistent state partway through its construction
    • It does not enforce consistency and validity checks

Builder pattern does not suffer from the above problems.

The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. – Gof

So instead of creating the desired object directly, the client calls a constructor with all the required parameters and gets a builder object. The client then calls chained (methods that return this) setter-like methods  on the builder to set the optional parameters of interest. Finally, the client calls a parameterless build method to create the object, which is always immutable.

Advantages:

  • Encapsulates the way a complex object is constructed
  • Allows objects to be constructed in a multistep and varying process
  • Helps to avoid long argument list
  • Helps to avoid mixing constructor arguments

Drawback:

  • Constructing objects requires more domain knowledge of the client than using a Factory.

Example:

public class Pet {
    public static class Builder {
        private final Pet pet = new Pet();

        public Builder withPetName(final String petName) {
            pet.petName = petName;
            return this;
        }

        public Builder withOwnerName(final String ownerName) {
            pet.ownerName = ownerName;
            return this;
        }

        public Builder withAddress(final String address) {
            pet.address = address;
            return this;
        }

        public Builder withDateOfBirth(final String dateOfBirth) {
            pet.dateOfBirth = dateOfBirth;
            return this;
        }

        public Builder withEmailAddress(final String emailAddress) {
            pet.emailAddress = emailAddress;
            return this;
        }

        public Builder withPhoneNumber(final String phoneNumber) {
            pet.phoneNumber = phoneNumber;
            return this;
        }

        public Pet build() {
            if(pet.petName == null) {
                throw new NullPointerException("Pet name is null");
            }
            return pet;
        }
    }

    private String petName;
    private String ownerName;
    private String address;
    private String dateOfBirth;
    private String emailAddress;
    private String phoneNumber;

    @Override
    public String toString() {
        return "Pet{" +
                "petName='" + petName + '\'' +
                ", ownerName='" + ownerName + '\'' +
                ", address='" + address + '\'' +
                ", dateOfBirth='" + dateOfBirth + '\'' +
                ", emailAddress='" + emailAddress + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                '}';
    }
}

 Test

public class PetTest {

    @Test
    public void validPetBuild(){

        Pet.Builder builder = new Pet.Builder();

        Pet pet = builder.withPetName("kiko")
                .withAddress("123 Main Street")
                .withDateOfBirth("12-02-1978")
                .withEmailAddress("test@hotmail.com")
                .withOwnerName("John")
                .withPhoneNumber("3434232")
                .build();

        Assert.assertNotNull(pet);
    }
}
Advertisements
Builder Pattern

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s