Skip to content

Instantly share code, notes, and snippets.

@miladvafaeifard
Last active December 1, 2018 23:40
Show Gist options
  • Save miladvafaeifard/23be1d5788115b6faa70ba4d6c9d2a3e to your computer and use it in GitHub Desktop.
Save miladvafaeifard/23be1d5788115b6faa70ba4d6c9d2a3e to your computer and use it in GitHub Desktop.
understand factory pattern in plain javascript
class Animal {
constructor(pet) {
this.pet = pet;
}
speak() {
console.log(this.pet);
}
join(animal) {
this.pet = `${this.pet} joined to ${animal.pet}`;
return this;
}
}
class Cat extends Animal {
constructor(number) {
super('😎'.repeat(number));
}
}
class Dog extends Animal {
constructor(number) {
super('πŸ±β€'.repeat(number));
}
}
class Bird extends Animal {
constructor(number) {
super('🐀'.repeat(number));
}
}
const ANIMAL = {
BIRD: 'BIRD',
CAT: 'CAT',
DOG: 'DOG',
DEFAULT: 'DEFAULT',
}
const Animals = {
[ANIMAL.CAT]: (num) => new Cat(num),
[ANIMAL.DOG]: (num) => new Dog(num),
[ANIMAL.BIRD]: (num) => new Bird(num),
[ANIMAL.DEFAULT]: () => { throw chalk.bgRed('Sorry, we don\'t have pet you wished') }
}
const AnimalFactory = (animal, num) => {
return (Animals[animal] || Animal[ANIMAL.DEFAULT])(num);
}
const adoptPet = (pet, num = 0) => {
return AnimalFactory(pet, num);
}
adoptPet(ANIMAL.BIRD, 3).speak();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment