Builder Design Pattern

1. Definition

The following is the definition of Builder Patter from wikipedia.

The Builder is a design pattern designed to provide a flexible solution to various object creation problems in OOP. The intent of it is to separate the construction of a complex object from its representation.

2. What problem the Builder sloves ?

The Builder design pattern describes how to solve such problem.

  • Encapsulate creating and assembling the parts of a complex object in a seperate Builder object.
  • A class delegates object creation to a Builder object instead of creating objects directly.
    A class can delegate to different Builder objects to create different representations of a complex object.

3. Advantages

  • Provide very readable, betterthan infinite number of constructors with boolean or numeric arguments, or setters.
  • Eliminates ‘telescoping’ constructors without sacrificing immutability.
  • Allows you to vary a product’s internal representation.
  • Encapsulates code for construction and representation.
  • Provides control over steps of construction process.

4. Example

Example
public class BankAccount {

    // account id
    private long accountNumber;

    // owner name
    private String owner;

    // balance amount
    private double balance;

    // branch name
    private String branch;

    // interest rate
    private double interestRate;

    // getters and setters

    /*
    * private constructor
    * so users cannot instantiate a new account by calling the constructor directly
    *
    * */
    private BankAccount(Builder builder) {
        this.accountNumber = builder.accountNumber;
        this.owner = builder.owner;
        this.balance = builder.balance;
        this.branch = builder.branch;
    }

    @Override
    public String toString() {
        return "BankAccount{" +
                "accountNumber=" + accountNumber +
                ", owner='" + owner + '\'' +
                ", balance=" + balance +
                ", branch='" + branch + '\'' +
                ", interestRate=" + interestRate +
                '}';
    }

    /*
    * The inner static Builder class
    *
    * */
    public static class Builder {

        // fields we want to use to create a new bank account
        // account id, required
        private long accountNumber;

        // owner name
        private String owner;

        // balance amount
        private double balance;

        // branch name
        private String branch;

        /*
        * constructor
        * construct the Builder with account id
        *
        * */
        public Builder(long accountNumber) {
            this.accountNumber = accountNumber;
        }

        public Builder withOwner(String owner) {
            this.owner = owner;
            return this;
        }

        public Builder openingBalance(double balance) {
            this.balance = balance;
            return this;
        }

        public Builder atBranch(String branch) {
            this.branch = branch;
            return this;
        }

        public BankAccount build() {
            return new BankAccount(this);
        }
    }

}

Note that in the inner class Builder, this refers to the inner class object and build() methods returns a bankAccount instance.

By using the Builder pattern, new we can create a bank account like this.

public static void main(String[] args) {
    BankAccount bankAccount = new BankAccount.Builder(10L)
            .withOwner("TongTongShi")
            .atBranch("AB, CA")
            .openingBalance(123.456)
            .build();
}

   Reprint policy


《Builder Design Pattern》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC