[ Ad Placement: Top Article Banner ]
Design Patterns: Singleton & Factory in TS
The Singleton Pattern
A Singleton ensures that a class has only one instance globally and provides a single point of access to it. This is perfect for a Database Connection pool or a Logger class. In TypeScript, you make the constructor private and provide a static getInstance() method.
class Database {
private static instance: Database;
private constructor() { /* Connect */ }
public static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
}The Factory Pattern
Instead of calling new everywhere in your codebase (which tightly couples your code to specific classes), you create a Factory. If you need to generate different types of UI Buttons (WindowsButton, MacButton), you pass a string to the Factory (ButtonFactory.create("mac")). The Factory contains the messy conditional logic, returning the correct object, keeping the rest of your application completely ignorant of the specific implementations.
[ Ad Placement: Bottom Article Banner ]