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
Loading Code Playground...
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?