Skip to content

Instantly share code, notes, and snippets.

@kirilloid
Created March 18, 2016 16:52
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 kirilloid/04b35c95008a26f7e02a to your computer and use it in GitHub Desktop.
Save kirilloid/04b35c95008a26f7e02a to your computer and use it in GitHub Desktop.
es6 patterns
class Shape {
constructor (type, ...args) {
super();
switch (type) {
case 'rect':
return new Rectangle(...args);
case 'circle':
return new Circle(...args);
}
}
}
class Circle extends Shape {
constructor (radius) {
this.radius = radius;
}
surface () {
return Math.PI * this.radius ** 2;
}
}
class Rect extends Shape {
constructor (width, height) {
this.width = width;
this.height = height;
}
surface () {
return this.width * this.height;
}
}
// factory method (Static Factory)
Shape.create('circle', [4]);
// abstract factory
new Shape.CircleFactory().create(4);
new Shape.RectFactory().create(5, 3);
new Shape('circle', 4);
new Shape('rect', 5, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment