Builder Design Pattern

Builder Design Pattern is a design pattern, which is used to create object from a complex or from a general object. Whenever someone creates a Builder Pattern, main class will be unaware about the pattern which means the creation of Builder Pattern is independent.

class UserFullName {
  constructor(name) {
    this.fullName = name
  }
}

class UserBuilder {
  constructor(name) {
    this.user = new UserFullName(name);
  }

  setUsername(username) {
    this.user.username = username;
    return this;
  }

  setEmail(email) {
    this.user.email = email;
    return this;
  }

  setPassword(password) {
    this.user.password = password;
  }
}

Now we can create object based on property we have.

const user_builder = new UserBuilder('John Doe')
                     .setUsername('doe')
                     .setEmail('doe@gmail.com');

We can set username or email or password, they are optional in that case. Then the user_builder or builder object will be,

UserBuilder {
  user: UserFullName {
    fullName: 'John Doe',
    username: 'doe',
    email: 'doe@gmail.com'
  }
}

Advantages of Builder Design Pattern

  • Allows you to create simple object from complex class.
  • Allows you to vary internal representation of a class.

Disadvantages of Builder Design Pattern

  • Requires creating a separate builder for each different type of class.

3 thoughts on “Builder Design Pattern”

Leave a Comment

Your email address will not be published. Required fields are marked *