Usefall

The Factory Method Pattern

Purpose

Something is created then other things are happening.

I want to change what is created without affecting the other things.


Duck Summoner

I have got but one method,

I create ducks then use them to defeat my enemies.

class DuckSummoner {
  attack() {
    const duck = new Duck();

    console.log("Bibidi Magic! Attackus my enemy!");
    duck.attackMyEnemy();
  }
}

Son of Duck Summoner

I wanna join you in battle dad…

But I don’t like ducks, I like tigers!

class Son extends DuckSummoner {}

Duck Summoner

Just override my attack method,

but summon your tiger instead.

class Son extends DuckSummoner {
  attack() {
    const tiger = new Tiger();

    // What was the magic chant again?
  }
}

Son of Duck Summoner

I tried dad.

But that made me forget how to do the magic chant and the rest.

I only want to change creature creation, without affecting anything else.

Duck Summoner

Oh. I will move creature creation to a separate method summonCreature.

Try overriding the factory method summonCreature instead.

class DuckSummoner {
  summonCreature() {
    return new Duck();
  }

  attack() {
    const creature = this.summonCreature();

    console.log("Bibidi Magic! Attackus my enemy!");
    creature.attackMyEnemy();
  }
}
class Son extends DuckSummoner {
  summonCreature() {
    return new Tiger();
  }
}

Son of Duck Summoner

I think that will work dad.

Let’s try attacking together!

const duckSummoner = new DuckSummoner();
const son = new Son();

duckSummoner.attack();
son.attack();

Son of Duck Summoner

Woah!!! it works!

I can now attack using tigers while you use ducks!!!

Thanks dad!

Duck Summoner

You are welcome duckling.


Solution

Dedicate a separate method for object creation (the factory method).

Other code can override this function without affecting anything else.


Notes, Credits and References