Skip to content

Instantly share code, notes, and snippets.

@zimejin
Last active May 26, 2019 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zimejin/00e237604b0b76a426d514d11af03e06 to your computer and use it in GitHub Desktop.
Save zimejin/00e237604b0b76a426d514d11af03e06 to your computer and use it in GitHub Desktop.
Factory design pattern
// Animal factory
const Animal = function(name){
const animal = {};
animal.name = name;
animal.walk = function(){
console.log(this.name + " walks");
}
return animal;
};
// Robot factory
const Robot = function(name) {
const robot = {}
robot.name = name;
robot.speak = function(message) {
console.log(robot.name + " speaks " + message)
}
return robot;
}
// Mixins
const canKill = {
kill() {
console.log("I can kill")
}
}
const canFly = {
fly(h) {
console.log("I can fly " + h "meters high")
}
}
const canDance = {
dance() {
console.log("Look Maa !! I'm dancing")
}
}
// End Mixins
// note the Object.assign() method in manipulating objects
k1 = Object.assign(Animal("k1"), canKill)
brian = Object.assign(Animal("brian"), canKill, canFly, canDance)
roboDog = Object.assign(Animal("roboDog"), Robot("roboDog"))
k1.kill();
k1.walk();
brian.walk()
brian.fly(200)
brian.kill()
brian.dance()
killingRoboDog = Object.assign({}, roboDog, canKill)
killingRoboDog.walk()
killingRoboDog.kill()
killingRoboDog.speak("roboDog will kill you")
// resources https://medium.com/front-end-weekly/understand-the-factory-design-pattern-in-plain-javascript-20b348c832bd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment