DEV Community

loading...

Builder Pattern in Javascript — With a Simple Example

yashsharma04 profile image Yash Sharma ・2 min read

Many times, we may come across a scenario where we want to construct complex objects which involves computing multiple sequential operations. In such a scenario, a builder pattern can be used.

Builder Pattern: A Design Pattern that lets us extract the object construction out of its own class (its representation) so that it can be used for multiple different representations.

One advantage to use this pattern is, it lets us build objects with one operation on top of another where we don’t need to call all operations at a time, only the ones that are needed to produce a particular output.

In this article, we will go through a simple example as to how to implement builder pattern in Javascript.

Let’s say we want to do something like
let calculator = new Calculator()
let result = calculator.add(5).subtract(1).divide(2).compute()

This instantiates a calculator and performs multiple operations on top of one another and finally compute something.

Here’s how we can achieve this using Builder pattern

class Calculator {
  constructor(props){
    super(props);
    this.result = 0 ;
  }

  add = (number) => {
    this.result = this.result + number ;
    return this ;
  }

  subtract = (number) => {
    this.result = this.result - number ;
    return this;
  }

  divide = (number) => {
    this.result = this.result / number ;
    return this;
  }

  multiply = (number) => {
    this.result = this.result * number ;
    return this;
  }

  compute = () => {
    return this.result;
  }
}

When we call new Calculator(), the result is instantiated with 0 and then any number of operations can be performed on top of it, to compute the final result.

The part to focus here, is that the instance is returned from every method (every computation) and is then used to build up the complex object. This way the method calls can be chained. This chaining of method calls is known as fluent API Understanding Fluent APIs.

This gives us a gist of how builder pattern works and how it can be used in different scenarios.

Original posted on https://medium.com/swlh/builder-pattern-in-javascript-e5b13e4e51af

Discussion

pic
Editor guide