class Shape { constructor(ctx) { this.ctx = ctx; } draw() { throw new Expection("Not implemented"); } } class Circle extends Shape { draw() { this.ctx.beginPath(); this.ctx.arc(100, 75, 50, 0, 2*Math.PI); this.ctx.stroke(); } } class Square extends Shape { draw() { this.ctx.rect(20,20,100,100); this.ctx.stroke(); } } class ShapeFactory { getShape(type, ctx) { switch(type) { case "Circle": return new Circle(ctx); case "Square": return new Square(ctx); default: throw new Exception("Type not found"); } } } // Imagine this is in another file, that has no access to Shape, Square, or Circle, // but does have access to ShapeFactory const c = document.getElementById("canvas"); const ctx = c.getContext("2d"); const sf = new ShapeFactory(); const circle = sf.getShape("Circle", ctx); const square = sf.getShape("Square", ctx); circle.draw(); square.draw();
<canvas id="canvas" width="500px" height="500px"></canvas>
canvas { background-color: white; border: 1px solid black; }