TypeScript
/Intermediate
Singleton Pattern (TS)
Definition
A creational design pattern that restricts the instantiation of a class to one single instance, enforcing strict typing on that instance globally.
Explain Like I'm New
Imagine the Database of your app. You don't want 50 different files opening 50 different connections to the database. The Singleton pattern hides the `new Database()` constructor, and provides a `.getInstance()` method. The first time it's called, it connects. Every time after that, it hands out the exact same connection.
Real World Example
Creating a global logger or a configuration manager. `const logger = Logger.getInstance(); logger.log('Hello');`
Common Use Cases
- •Database connection pools
- •Global application state (pre-Redux)
- •Hardware interface access
Interactive Example
class Database { // 1. Static property to hold the single instance private static instance: Database; // 2. PRIVATE constructor prevents 'new Database()' private constructor() { console.log("Initializing Database Connection..."); } // 3. Static method controls access to the instance public static getInstance(): Database { if (!Database.instance) { Database.instance = new Database(); } return Database.instance; } public query(sql: string) { console.log(`Executing: ${sql}`); } } // ERROR: Constructor of class 'Database' is private // const db = new Database(); const db1 = Database.getInstance(); // Prints: Initializing Database... const db2 = Database.getInstance(); // Doesn't print anything! console.log(db1 === db2); // true (Exact same object in memory)
Interview Questions
basic
- How do you prevent a developer from writing `new Singleton()`?
intermediate
- What is the `static` keyword used for in a Singleton?
advanced
- Why do many developers consider Singletons an anti-pattern in React?