DEV Community

loading...
Cover image for Master Design Patterns By Building Real Projects - Builder Pattern - Javascript

Master Design Patterns By Building Real Projects - Builder Pattern - Javascript

hieptl profile image Hiep Le ・Updated on ・3 min read

Creational Pattern - Builder Pattern.

This is the third part in my series (23 GoF Design Patterns). My series will help you understand about design patterns by building real projects. For this reason, you can see the places in which each pattern could be applied. I want to focus on learning by doing instead of talking too much about theories.

I'm Hiep. I work as a full-time software engineer. Most of my open-source projects are focused on one thing - to help people learn 📚.

I created a git repository that help you understand about design patterns by building real projects.

Github link:

https://github.com/hieptl/javascript-dessign-patterns

If the repository is useful, please help me share the post and give me a Github's star. It will make me feel motivation to work even harder. I will try to make many open sources and share to the community ❤️.

I also created some series that help you improve your practical skills ❤️

1. Learn React By Building Netflix

https://dev.to/hieptl/learn-react-by-building-netflix-1127

Table of Contents

1. Definition.

Builder pattern will help you to separate the construction of a complex object from its representations. We can reuse the same construction process to create various representations.

We can feel free to add properties to an object in different ways by using Javascript, for example, you can use object literal syntax and write something like this:

const cake = {};
cake.hasSugar = true;
cake.hasStrawberry = true;
...

However, we should build by ourselves to understand about the core concepts. Therefore, we will feel more interested in programming and increase logical thinking.

2. Scenarios.

We can imagine that we have a bakery. We need to make different cakes by following the requirements from the customers.

As mentioned before, We can achieve the result in different ways in Javascript. However, we will create the solution by using Builder pattern.

3. Building a Bakery.

I want to use Javascript class to implement the idea because in the case you are using object-oriented programming languages or you have to use those languages in the future, you can still implement design patterns by using different languages. In my opinion, design patterns are mindset and approaches and not depend on programming languages.

Our classes will be looked like this:

class Cake {
  // you can put other properties for your cake <3.
  // I use sugar and strawberry for the demo purpose.
  constructor(hasSugar, hasStrawBerry) {
    this.hasSugar = hasSugar;
    this.hasStrawBerry = hasStrawBerry;
  }
}

class CakeBuilder {
  constructor() {
    this.cake = new Cake();
  }

  withSugar(hasSugar) {
    this.cake.hasSugar = hasSugar;
    return this;
  }

  withStrawberry(hasStrawBerry) {
    this.cake.hasStrawBerry = hasStrawBerry;
    return this;
  }

  makeCake() { 
    return this.cake;
  }
}

const firstCakeBuilder = new CakeBuilder();

const cake = firstCakeBuilder
.withSugar(true)
.withStrawberry(true)
.makeCake();

console.log(cake);
Enter fullscreen mode Exit fullscreen mode

Step 1: We create Cake class. The constructor of the class accepts hasSugar and hasStrawberry properties as parameters. (You can add more properties for your cake, two properties are used for the demo purpose 😄).

Step 2: We create CakeBuilder class. In the constructor of the class, a new cake object will be created. On the other hand, we create methods to build the corresponding properites for the cake object, for example, we have withSugar to build hasSugar property, withStrawberry to build hasStrawberry property and so on. If you have many properties, you just need to create more methods to build values for those properties.

Step 3: We create makeCake method. The method will not be used to build value for any properties. It is used to return the final cake instance.

Step 4: In order to use the cake builder, we need to create a new object of CakeBuilder class. By invoking different methods from cakeBuilder object, we are building properties for our cake. Please do not forget about makeCake method. It will return the final cake for us. The last but not least, we assign the final result to cake variable and then you can do everything you want with your cake.

const cakeBuilder = new CakeBuilder();

const cake = cakeBuilder
.withSugar(true)
.withStrawberry(true)
.makeCake();
Enter fullscreen mode Exit fullscreen mode

4. Result.

Cake { hasSugar: true, hasStrawBerry: true }
Enter fullscreen mode Exit fullscreen mode

The above result describes that the final cake is created by applying Bulider pattern.

By using design patterns, we can understand the core concepts and make our code become more readable and cleaner. I hope that the post can help you understand about Builder pattern.

Thanks and Best Regards,
Hiep.

Discussion (5)

Collapse
miguelbarcelo profile image
MiguelBarcelo

But, what happen when you create the new object this.cake = new Cake(); if the class Cake constructor its waiting for two parameters. Thank you!

Collapse
hieptl profile image
Hiep Le Author • Edited

Hi @miguelbarcelo , Thank you for your question ❤️

const cake = firstCakeBuilder
.makeCake();
Enter fullscreen mode Exit fullscreen mode

The above code demonstrates that we did not specify any properties for the cake. In that case, hasSugar and hasStrawberry will be undefined.

Cake { hasSugar: undefined, hasStrawBerry: undefined }
Enter fullscreen mode Exit fullscreen mode

Let's consider another example:

const cake = firstCakeBuilder
.withStrawberry(true)
.makeCake();
Enter fullscreen mode Exit fullscreen mode

If we run the above code, the result will be:

Cake { hasSugar: undefined, hasStrawBerry: true }
Enter fullscreen mode Exit fullscreen mode

According to the business requirements, I think it is make sense because if any property is undefined, it means that we do not want to include that property in the cake and the baker can know about what should be included in the cake.

We can try another example without the builder pattern.

class Cake {
    constructor(hasSugar, hasStrawberry) {
    this.hasSugar = hasSugar;
    this.hasStrawberry = hasStrawberry;
  }
}
const cake = new Cake();
console.log(cake);
Enter fullscreen mode Exit fullscreen mode

The result of the above code will be:

{
  hasStrawberry: undefined,
  hasSugar: undefined
}
Enter fullscreen mode Exit fullscreen mode

The values of hasSugar and hasStrawberry are undefined, if we do not specify values for them.

Thanks and Best Regards,
Hiep.

Collapse
miguelbarcelo profile image
MiguelBarcelo

Hi Hiep Le! Thanks for you answer!

BR,
Miguel.

Collapse
srikanth597 profile image
srikanth597

Nice, I liked it.
I see lot of builder pattern when I explore Java projects.
Now I get the idea.
The key here is returning this instance on every method.

Collapse
hieptl profile image
Hiep Le Author

Hi @srikanth597 , Thank you so much ❤️ I am writing the next parts for this series. I hope that my series could help the developers understand about design patterns and apply them in their works.

On the other hand, I am writing about other topics such as Javascript, React and so on. If you feel my posts are useful, please help me share them to the community ❤️

Thanks and Best Regards,
Hiep

Forem Open with the Forem app