Skip to content

Instantly share code, notes, and snippets.

@drenther
Created July 1, 2018 15:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drenther/69dbcd2a4490958c60268e8b3458c0d1 to your computer and use it in GitHub Desktop.
Save drenther/69dbcd2a4490958c60268e8b3458c0d1 to your computer and use it in GitHub Desktop.
Creational Pattern - Factory
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