Usefall

The Builder Pattern

Purpose

A complex thing needs to be created.

I want to simplify its creation.


Leopard

I really want to build a fancy house but it’s too complicated!

class House {
  construct(material, doors, windows) {
    this.material = material;
    this.doors = doors;
    this.windows = windows;
  }
}

Leopard

Lightning Sloth, please help me!

Lightning Sloth

Sure. Describe the house you want to me.

class LightningSlothTheBuilder {
  houseMaterial;
  doors = [];
  windows = [];

  madeOf(material) {
    this.houseMaterial = material;
    return this;
  }

  withDoor(material) {
    this.doors.push(new Door(material));
    return this;
  }

  withWindow(material) {
    this.windows.push(new Window(material));
    return this;
  }
}

Leopard

The house should be made of dirt.

It should have a door made of diamond.

It should have a door made of emerald.

It should have a window made of steel.

const lightningSlothTheBuilder = new LightningSlothTheBuilder();

const leopardHouse = lightningSlothTheHouseBuilder
  .houseMaterial("dirt")
  .withDoor("diamond")
  .withDoor("emerald")
  .withWindow("steel");

Lightning Sloth

All done!

Leopard

What!? How did you finish so fast!?

Lightning Sloth

I focused on noting down all the things you described,

gradually, one by one, step by step.

Everytime I noted something down,

I returned myself so I can note the next thing.

Then I finally built the house.

Leopard

Wow thanks! You are so cool!

Lightning Sloth

I know. Sometimes you gotta go slow to go fast. Hehe.


Solution

Have a separate thing gradually handle object creation (a builder).

Gradually describe all the parts that are needed to the builder, finally tell the builder to create the thing you want.


Credits and References