Builder Pattern

The builder pattern allows for the creation of a complex object in a procedural manner.

Imagine a scenario where you’re creating an application that allows the user to build their own house. Since you want your users to like your product, you provide them a tremendous amount of options. They can add pools, gardens, internet, walls, and even a roof (imagine that, a real roof!). There are several ways to approach this from a code perspective.

The first solution is by creating a monster constructor for the House class. This constructor can accept a massive list of parameters that define what properties a given House class has. This has an obvious drawback. As more options are added the constructor grows accordingly; very quickly creating an ugly constructor. Additionally, many times, some parameters will not be used thereby adding unnecessary complexity to the House class.

class House {  
  constructor(walls, pool, roof, garden, internet, ...) {...}
}

The second solution is using classical inheritance. You can create a base House class, and create sub-classes for every variation from there. You can probably tell right away that this approach won’t scale at all. The more options you add to the house (like a bathroom perhaps), the more sub-classes you’ll need to add.

#gang-of-four #javascript #builder-pattern #design-patterns #programming

Deep Dive Into Design Patterns With JavaScript. The Builder Pattern
3.80 GEEK