JavaScript Builder Pattern Example

The builder pattern is a creational design pattern used to create objects. It builds a complex object using simple objects by providing a step by step approach. Builder pattern uses fluent API to create objects.

JavaScript Builder Pattern Example

The example creates an object using the builder design pattern.
let User = function (firstName, lastName, email) {

    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
}

let UserBuilder = function () {

    let firstName;
    let lastName;
    let email;

    return {
        setFirstName: function (firstName) {
            this.firstName = firstName;
            return this;
        },
        setLastName: function (lastName) {
            this.lastName = lastName;
            return this;
        },
        setEmail: function (email) {
            this.email = email;
            return this;
        },
        info: function () {
            return `${this.firstName} ${this.lastName}, ${this.email}`;
        },
        build: function () {
            return new User(firstName, lastName, email);
        }
    };
};

var user = new UserBuilder().setFirstName('Ramesh').setLastName('Fadatare')
    .setEmail('[email protected]');
console.log(user.info());
Output:
Ramesh Fadatare, [email protected]

Demo


For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.

Comments