← back to the blog


JavaScript Factory Design Pattern (using ES6 class)

Posted on April 16th, 2020 in JavaScript, NodeJS by George

 

A quick example of how to implement the factory pattern in Javascript using ES6 classes.

The factoryAthletes is a function that encapsulates what is needed to create different objects based on the desired type.

For the sake of simplicity, I have used athletes as an example.

Enough with words let's look at some code.

 

class Footballer {
  constructor(name, club) {
    this.name = name;
    this.club = club;
  }

  get nameAndClub(){
    return `${this.name}  -  ${this.club}`;
  }
}


class Basketballer {
  constructor(name, club) {
    this.name = name;
    this.club = club;
  }

  get nameAndClub(){
    return `${this.name}  -  ${this.club}`;
  }
}


//factoryAthletes function implements the factory building pattern because encapsulates 
//everything is needed to create a new object from different classes

var factoryAthletes = (name, type, club) => {
  switch (type) {
    case 'Footballer':
      return new Footballer(name, club);
    case 'Basketballer':
      return new Basketballer(name, club);
  }
};

//Tests 

let ilie = factoryAthletes('Ilie Smith', 'Footballer' ,'Norwich FC');
let dorin = factoryAthletes('Dorin Constantin', 'Basketballer', 'London BC');

//Output

console.log(ilie.nameAndClub);
console.log(dorin.nameAndClub);

 

Thank you and stay safe.