Design Pattern Factory With Typescript
/ 1 min read
Table of Contents
Summary
In this post I will show example design pattern Factory with Typescript.
The Factory pattern provide one of the best ways to create an object.
Refer from tutorial
Getting started
In this post we will use Typescript Playground to easy setup typescript.
Example
- Create an interface
interface IShape { draw(): void}- Create class implement interface
class Rectangle implements IShape { draw() { console.log('Rectangle'); }}
class Square implements IShape { draw() { console.log('Square'); }}
class Circle implements IShape { draw() { console.log('Circle'); }}- Create factory class
enum ShapeType { RECTANGLE = 'RECTANGLE', SQUARE = 'SQUARE', CIRCLE = 'CIRCLE',}
class ShapeFactory { getShape(shapeType: string): IShape | null { switch (shapeType) { case ShapeType.RECTANGLE: return new Rectangle(); case ShapeType.SQUARE: return new Square(); case ShapeType.CIRCLE: return new Circle(); default: return null; } }}- Use Factory Class to get instance of the class
const shapeFactory = new ShapeFactory();
const rec = shapeFactory.getShape(ShapeType.RECTANGLE);const square = shapeFactory.getShape(ShapeType.SQUARE);const circle = shapeFactory.getShape(ShapeType.CIRCLE);- Verify output
(rec as IShape).draw();(square as IShape).draw();(circle as IShape).draw();[LOG]: "Rectangle"[LOG]: "Square"[LOG]: "Circle"