Originally published on Hackdoor

A Design Pattern describes an established solution to the most commonly encountered problems in software design. Let's dig deep into creational patterns in ES6+ using Game of Thrones!

In software engineering, a Design Pattern describes an established solution to the most commonly encountered problems in software design. It represents the best practices evolved over a long period -through trial and error- by experienced software developers.

In this article we will talk about the Creational Design Patterns. Creational Patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.

The most common Creational Patterns are:

Factory Method Pattern

The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. Wait, What does this mean?

Let’s pretend that we want to be able to create soldiers. These soldiers can be from the Targaryen’s house or from the Lannister’s house.

According to the "Factory Method" pattern, we will need:

class Soldier {
  constructor(name) {
    this.name = name;
    this.attack = this.attack.bind(this);
  }

  attack() {}
}

class LannisterSoldier extends Soldier {
  attack() {
    return "A Lannister always pays his debts";
  }
}

class TargaryenSoldier extends Soldier {
  attack() {
    return "Fire and blond";
  }
}

class Spawn {
  constructor(type, name) {
    if (type === "lannister") return new LannisterSoldier(name);
    else return new TargaryenSoldier(name);
  }
}

(() => {
  const lannister = new Spawn("lannister", "soldierA");
  const targaryen = new Spawn("targaryen", "soldierB");
  console.log(lannister.attack());
  console.log(targaryen.attack());
})();

When to use the Factory Method Pattern?