Created
July 1, 2018 15:19
-
-
Save drenther/69dbcd2a4490958c60268e8b3458c0d1 to your computer and use it in GitHub Desktop.
Creational Pattern - Factory
This file contains 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 BallFactory { | |
constructor() { | |
this.createBall = function(type) { | |
let ball; | |
if (type === 'football' || type === 'soccer') ball = new Football(); | |
else if (type === 'basketball') ball = new Basketball(); | |
ball.roll = function() { | |
return `The ${this._type} is rolling.`; | |
}; | |
return ball; | |
}; | |
} | |
} | |
class Football { | |
constructor() { | |
this._type = 'football'; | |
this.kick = function() { | |
return 'You kicked the football.'; | |
}; | |
} | |
} | |
class Basketball { | |
constructor() { | |
this._type = 'basketball'; | |
this.bounce = function() { | |
return 'You bounced the basketball.'; | |
}; | |
} | |
} | |
// creating objects | |
const factory = new BallFactory(); | |
const myFootball = factory.createBall('football'); | |
const myBasketball = factory.createBall('basketball'); | |
console.log(myFootball.roll()); // The football is rolling. | |
console.log(myBasketball.roll()); // The basketball is rolling. | |
console.log(myFootball.kick()); // You kicked the football. | |
console.log(myBasketball.bounce()); // You bounced the basketball. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment