DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
  • Angular Apps Don’t Need Another Chatbot: Building Agentic UI Workflows With TypeScript
  • Text Analysis Without a Backend: Replacing an LLM Call With Intl.Segmenter and 60 Lines of JavaScript

Trending

  • DZone's Article Submission Guidelines
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • Part 4: Multi-Agent Orchestration — Pairing Goose With Quarkus Flow State Machines
  • The SDLC After AI

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. JavaScript
  4. Builder Pattern in Javascript

Builder Pattern in Javascript

Initialize objects with more human-readable code in a few, simple steps.

By 
Souradip Panja
·
Sep. 12, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

legos-scattered-on-wooden-floor

For those who don't care about code readability: step on a lego

Suppose we go to a store and want to buy a product. Let’s say a PC. We have two options; either buy a ready-made PC of any particular brand, or we customize and assemble it.

In this scenario, we go for the second option — we will collect different parts and construct a new PC.

You may also like: Design Patterns for Beginners With Java Examples.

Now, the person who is building the PC is basically the builder who knows which part to assemble to make it the computer functional. This person in terms of design patterns is known as the Builder pattern.

A Builder pattern is generally in charge of:

  • Simplifying the construction of an object.

  • Separating the construction and representation of that object.

  • Composition.

  • Creating different representations for the constructed object.

Let’s take a simple example

Course.js

class Course { 
  constructor(name, sales, isFree = false, price, isCampain = false) { 
    this.name = name; 
    this.sales = sales || 0; 
    this.isFree = isFree; 
    this.price = price || 0; 
    this.isCampain = isCampain;  // Advertising Campaign 
  } 
  
  toString() { 
    return console.log(JSON.stringify(this)); 
  } 
}

module.exports = Course; 


main.js

const Course = require('./course');  
  
const course_1 = new Course('Design Patterns 1', 0, true, 149 , true);  
const course_2 = new Course('Design Patterns 1', 0,false, 0, false);  
  
course_1.toString();  
course_2.toString();  


Now, if anyone observes this line,

const course_1 = new Course('Design Patterns 1', 0, true, 149 , true); 


will they be able to say what 0, true, 149, true signifies? Surely not. They have to go to the Course class constructor every time to see what value each parameter is tied to.

This problem can be easily solved by the Builder pattern. If the above line is represented in builder pattern, then it will look like

const course_1 = new CourseBuilder('Design Patterns 1').makePaid(100).makeCampain().build();  


Here, one can easily tell what parameters are required for the class.

Let’s build this above example with a builder pattern

  • Create a file for the builder (e.g. Coursebuilder.js)
  • Create a constructor with the parameter required. Use default values for best practice.
  • Create a function with meaningful names for the parameters used in the constructor.
  • Return the values used within the function. (i.e return this).
  • Create a method that will return the instance of the class for which the Builder class is made. In our example, we are creating a builder pattern for Course, so we will make a function that will return instance of the Course class with the values. We'll name it build().

CourseBuilder.js

const Course = require('./course');  
  
class CourseBuilder{  
    constructor(name, sales = 0, price = 0){  
        this.name = name;  
        this.sales = sales;  
        this.price = price;  
    }  
  
    makePaid(price){  
        this.isFree = false;  
        this.price = price;  
        return this;  
    }  
  
    makeCampain(){  
        this.isCampain = true;  
        return this;  
    }  
  
    build(){  
        return new Course(this);  
    }  
}  
  
module.exports = CourseBuilder;  


Now, in the main file instead of Course class, import the Coursebuilder class. Then, create an instance of it.

Main.js

const CourseBuilder = require('./CourseBuilder');  
  
//const course_1 = new CourseBuilder('Design Patterns 1', 0, true, 149 , true);  
//const course_2 = new CourseBuilder('Design Patterns 1', 0,false, 0, false);  
const course_1 = new CourseBuilder('Design Patterns 1').makePaid(100).makeCampain().build();  
const course_2 = new CourseBuilder('Design Patterns 2').build();  
  
course_1.toString();  
course_2.toString();  


Here, we can see that in the Builder pattern, the object creation code is less error-prone, as users will have a clear understanding of what parameters they are using.


Related Articles

  • Module Pattern in JavaScript. 
  • Domain-Driven Design in JavaScript. 

Builder pattern JavaScript

Opinions expressed by DZone contributors are their own.

Related

  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
  • Angular Apps Don’t Need Another Chatbot: Building Agentic UI Workflows With TypeScript
  • Text Analysis Without a Backend: Replacing an LLM Call With Intl.Segmenter and 60 Lines of JavaScript

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook