Last active
December 1, 2018 23:40
-
-
Save miladvafaeifard/23be1d5788115b6faa70ba4d6c9d2a3e to your computer and use it in GitHub Desktop.
understand factory pattern in plain javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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