Factory method design pattern JavaScript
What is factory design pattern?
A Factory Method creates new objects as instructed by the client. The Factory Method allows the client to delegate object creation while still retaining control over which type to instantiate.
A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate.
Example of factory method design pattern:
// AbstractProduct.ts export interface AbstractProduct { method(param?: any) : void; }
// ProductA.ts import {AbstractProduct} from "./AbstractProduct"; export class ProductA implements AbstractProduct { method = (param?: any) => { return "Method of ConcreteProductA"; } }
// ProductB.ts import {AbstractProduct} from "./AbstractProduct"; export class ProductB implements AbstractProduct { method = (param?: any) => { return "Method of ConcreteProductB"; } }
// FactoryMethod.ts import {AbstractProduct} from "./AbstractProduct"; import {ProductA} from "./ProductA"; import {ProductB} from "./ProductB"; export function getProductInstance(type: string) : AbstractProduct { if (type === "A") { return new ProductA(); } else if (type === "B") { return new ProductB(); } return null; }
// client.ts import {getProductInstance} from "./factoryMethod"; import {AbstractProduct} from "./AbstractProduct"; const a: AbstractProduct = getProductInstance("A"); const b: AbstractProduct = getProductInstance("B"); console.log(a.method()); // Method of ConcreteProductA console.log(b.method()); // Method of ConcreteProductB