TypeScript
/Intermediate
Factory Pattern (TS)
Definition
A pattern that provides an interface for creating objects in a superclass, but allows subclasses or logic gates to alter the type of objects that will be created.
Explain Like I'm New
A Factory is an automated vending machine. You don't need to know how the soda is made. You just press the 'Coke' button, and a Coke comes out. The Factory function abstracts away the messy `new` keywords and complex setup logic.
Real World Example
Building an API service factory. You call `ApiServiceFactory.create('user')` and it returns an Axios instance fully pre-configured with the User API base URL and specific Auth headers.
Common Use Cases
- •Complex object initialization
- •Decoupling implementation from usage
Interactive Example
// 1. The Common Interface interface Notification { send(msg: string): void; } // 2. The Concrete Implementations class EmailNotification implements Notification { send(msg: string) { console.log(`Sending Email: ${msg}`); } } class PushNotification implements Notification { send(msg: string) { console.log(`Sending Push: ${msg}`); } } // 3. The Factory class NotificationFactory { // The return type is the broad Interface, hiding the specific classes public static create(type: "email" | "push"): Notification { if (type === "email") return new EmailNotification(); if (type === "push") return new PushNotification(); throw new Error("Unknown notification type"); } } // Consumer code has no idea 'EmailNotification' class exists. // It just uses the factory. const notifier = NotificationFactory.create("email"); notifier.send("Welcome to the app!");
Interview Questions
basic
- Why use a Factory instead of just exporting multiple classes?
intermediate
- How do you type the return value of a Factory?
advanced
- What is an Abstract Factory in TypeScript?