Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Prototype Method - JavaScript Design Pattern
Next article icon

Builder Method | JavaScript Design Pattern

Last Updated : 08 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created.

Important Topics for the Builder Design Pattern in JavaScript Design Pattern

  • Example without using the Builder Design Pattern
  • Implementation of the above Example using Builder Design Pattern
  • Advantages of the Builder Design Pattern:
  • Disadvantages of the Builder Design Pattern:
  • Where to Use the Builder Design Pattern:
  • Where Not to Use the Builder Design Pattern:

Example without using the Builder Design Pattern

Let us take an example without using the Builder Design Pattern:

JavaScript
class User {                                    
  constructor(name , age , weight , address , gender) {                           
    this.name = name;
    this.age = age;
    this.weight = weight;
    this.address = address;
    this.gender = gender;
  }
  printUser() {
    return `User: { name: ${this.name}, age: ${this.age}, weight: ${this.weight}, address: ${this.address}, gender: ${this.gender} }`;
  }
}

const user  = new User('Abhishek' , 22 , 55 , 'India' , 'Male' );
console.log(user.printUser());

Explanation of the above example:

User Class Definition:

JavaScript
class User {
  constructor(name, age, weight, address, gender) {
    this.name = name;
    this.age = age;
    this.weight = weight;
    this.address = address;
    this.gender = gender;
  }
  printUser() {
    return `User: { name: ${this.name}, age: ${this.age}, weight: ${this.weight}, address: ${this.address}, gender: ${this.gender} }`;
  }
}


  • The User class is defined with a constructor that takes parameters for the user's name, age, weight, address, and gender. The constructor initializes the respective attributes.
  • The printUser method generates a formatted string representing the user's information.

Creating a User Instance:

const user = new User('Abhishek', 22, 55, 'India', 'Male');

This line creates an instance of the User class by calling the constructor with the specified values for name, age, weight, address, and gender.

Displaying User Information:

console.log(user.printUser());

This line calls the printUser method on the user instance, which generates a string containing the user's information and logs it to the console.

Output:

User: { name: Abhishek, age: 22, weight: 55, address: India, gender: Male }

Before we move to implementing Builder Method we have to analyze what is wrong with this and what issues are solved by implementing builder method, at first we see the above code we realized that this is a correct and easy way to create a new object but we have to provide all information during initialization. If we look closely at the line:

const user = new User('Abhishek' , 22 , 55 , 'India' , 'Male' );

we see that properties of this user object can be confusing, like sometime we can mistakenly give age instead of weight and weight instead of age . As our code size grows, we will have to look at the class to figure out which properties we have to provide when initializing a user object.

For all these problems we have a design solution called Builder Method.

Implementation of the above Example using Builder Design Pattern

Implementation user Class:

JavaScript
//Blueprint for creating a new user using User class

class User {                                    
  constructor(name) {                           
    this.name = name;
    this.age = null;
    this.weight = null;
    this.address = null;
    this.gender = null;
  }

  // Method to set Age of the user
  setAge(age) {                                 
      this.age = age;
      return this;   // Return the object for method chaining
    }
    
  // Method to set the Weight of the user
  setWeight(weight) {                          
    this.weight = weight;
    return this;    // Return the object for method chaining
  }

  // Method to set the Address of the user
  setAddress(address) {
    this.address = address;
    return this;   // Return the object for method chaining
  }
  // Method to set the gender of user
  setGender(gender) {
    this.gender = gender;
    return this;    // Return the object for method chaining
  }

  //Method to finalize the user creation
  build() {
    if (!this.name) {
      throw Error('Name is required');
    }
    return this;   // Return the object for method chaining
  }

  printUser() {
    return `User: { name: ${this.name}, age: ${this.age}, weight: ${this.weight}, address: ${this.address}, gender: ${this.gender} }`;
  }
}
// Usage
const user = new User('Abhishek').setAge(30).setGender('Male').build();

console.log(user.printUser());

Note: In build method, we have only checked for name but we can also add more checks

Explanation of the above example using Builder Design Pattern:

User Class Definition:

JavaScript
class User {
  constructor(name) {
    this.name = name;
    this.age = null;
    this.weight = null;
    this.address = null;
    this.gender = null;
  }
}


Here, a User class is defined with a constructor that takes a name parameter and initializes other user attributes (age, weight, address, gender) to null.

Setting User Attributes:

JavaScript
setAge(age) {
  this.age = age;
  return this; 
}
setWeight(weight) {
  this.weight = weight;
  return this; 
}
setAddress(address) {
  this.address = address;
  return this; 
}
setGender(gender) {
  this.gender = gender;
  return this;
}


These set methods allow you to set the user's age, weight, address, and gender. They update the corresponding attributes and return the object to enable method chaining.

Finalizing User Creation:

JavaScript
build() {
  if (!this.name) {
    throw Error('Name is required');
  }return this;     // Return the object for method chaining
}


The build method is used to finalize user creation. It checks if the name is provided and throws an error if it's not. It returns the object to allow method chaining.

Printing User Information:

JavaScript
printUser() {
  return `User: { name: ${this.name}, age: ${this.age}, weight: ${this.weight}, address: ${this.address}, gender: ${this.gender} }`;
}


The printUser method generates a string representation of the user's information.

Usage:

JavaScript
const user = new User('Abhishek').setAge(30).setGender('Male').build();
console.log(user.printUser());


This creates a new user with the name "Abhishek", sets the age to 30, and sets the gender to "Male". Then the build method is called to finalize user creation. Finally, the printUser method is used to print the user's information to the console.

Output:

User: { name: Abhishek, age: 30, weight: null, address: null, gender: Male }

Implementation using Function:

JavaScript
// Factory function to create a user object

function createUser(name) {

  const user = {
    name,
    age: null,
    weight: null,
    address: null,
    gender: null,

    // Method to set the age of the user
    setAge(age) {
      this.age = age;
      return this;     // Return the object for method chaining
    },

    // Method to set the weight of the user
    setWeight(weight) {
      this.weight = weight;
      return this;     // Return the object for method chaining
    },

    // Method to set the address of the user
    setAddress(address) {
      this.address = address;
      return this;    // Return the object for method chaining
    },

    // Method to set the gender of the user
    setGender(gender) {
      this.gender = gender;
      return this;   // Return the object for method chaining
    },

    // Method to finalize the user creation
    build() {
      if (!this.name) {
        throw Error('Name is required'); // Validate required properties
      }
      return this;   // Return the object for method chaining
    },

    // Method to display the user information as a string
    printUser() {
      return `User: { name: ${this.name}, age: ${this.age}, weight: ${this.weight}, address: ${this.address}, gender: ${this.gender} }`;
    }
  };

  return user;     // Return the user object
}

// Usage: Create a user object and set properties
const user = createUser('Abhishek')
  .setAge(30)
  .setWeight(70)
  .setAddress('India')
  .setGender('Male')
  .build();       // Finalize user creation

console.log(user.printUser());     // Display user information


Below is the explanation of the above code:

Factory Function to Create User Object:

JavaScript
function createUser(name) {
  const user = { ... };  // Object with user properties and methods
  return user;       // Return the user object
}


Here, a factory function createUser is used to create and initialize objects. The function takes a name parameter and returns a user object with properties and functions .

Setting User Attributes:

JavaScript
setAge(age) {
  this.age = age;
  return this; 
}
setWeight(weight) {
  this.weight = weight;
  return this; 
}
setAddress(address) {
  this.address = address;
  return this; 
}
setGender(gender) {
  this.gender = gender;
  return this;
}


These sets functions allow you to set the user's age, weight, address, and gender. They update the corresponding attributes and return the object to enable function chaining.

Finalizing User Creation:

JavaScript
build() {
  if (!this.name) {
    throw Error('Name is required');
  }return this;               // Return the object for method chaining
}


The build functions is used to finalize user creation. It checks if the name is provided and throws an error if it's not. It returns the object to allow function chaining.

Printing User Information:

JavaScript
printUser() {
  return `User: { name: ${this.name}, age: ${this.age}, weight: ${this.weight}, address: ${this.address}, gender: ${this.gender} }`;
}


The printUser function generates a string representation of the user's information.

Usage:

JavaScript
const user = new User('Abhishek').setAge(30).setGender('Male').build();
console.log(user.printUser());


  • This creates a new user with the name "Abhishek", sets the age to 30, sets the gender to "Male", sets the address to India and weight to 70.
  • Then build function is called to finalize user creation.
  • Finally, the printUser function is used to print the user's information to the console.

Output:

JavaScript
User: { name: Abhishek, age: 30, weight: 70, address: India, gender: Male }

Advantages of the Builder Design Pattern:

  • Improved Object Creation: The Builder pattern allows for the step-by-step construction of an object, making the creation process more understandable and manageable.
  • Flexible Object Construction: It provides flexibility by allowing different configurations for constructing objects.
  • Code Readability: The code using the Builder pattern is often more readable and self-explanatory, as method names in the builder convey the intention of the construction steps.

Disadvantages of the Builder Design Pattern:

  • Code Overhead: Implementing the Builder pattern requires creating a separate builder class or methods, which can introduce additional code and complexity.
  • Not Suitable for Simple Objects: For simple objects that do not have a significant number of properties or configurations, the Builder pattern may be overly complex.

Where to Use the Builder Design Pattern:

  • Complex Object Creation: Use the Builder pattern when dealing with complex objects that require multiple configurations and parameters for creation.
  • Object Initialization Flexibility: When you want to provide flexibility in the order of setting properties and handle optional parameters.

Where Not to Use the Builder Design Pattern:

Simple Objects: For objects with a small number of properties or minimal configuration requirements, the Builder pattern might introduce unnecessary complexity.


Next Article
Prototype Method - JavaScript Design Pattern

A

abhisheksahu20010525
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023
  • JavaScript Design Patterns

Similar Reads

    JavaScript Design Patterns Tutorial
    Design patterns in Javascipt are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best
    7 min read

    Creational Software Design Patterns in JavaScript

    Builder Method | JavaScript Design Pattern
    The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pa
    9 min read
    Prototype Method - JavaScript Design Pattern
    A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance
    3 min read
    Abstract Factory Pattern | JavaScript Design Patterns
    Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface
    6 min read

    Behavioural Software Design Patterns in JavaScript

    Template Method | JavaScript Design Patterns
    Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure
    10 min read
    State Method Design Patterns in JavaScript
    State method or State Design Patterns is a pattern that allows an object to alter its behavior when internal state changes occur. This pattern is used when an object wants to change its state dynamically. When we want to change behavior of object it internally uses if-else block to perform actions.
    4 min read
    Iterator Method | JavaScript Design Pattern
    Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is wi
    4 min read
    Strategy Method | JavaScript Design Pattern
    Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes t
    8 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences