Skip to content

Instantly share code, notes, and snippets.

@kirilloid
Created March 18, 2016 16:52
Show Gist options
  • Save kirilloid/04b35c95008a26f7e02a to your computer and use it in GitHub Desktop.
Save kirilloid/04b35c95008a26f7e02a to your computer and use it in GitHub Desktop.

Revisions

  1. kirilloid created this gist Mar 18, 2016.
    39 changes: 39 additions & 0 deletions factory.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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);