- Published on
Singleton
- Authors
- Name
- Khánh
Singleton
The Singleton pattern is different from the Single Responsibility principle defined in SOLID. The Singleton pattern is a design pattern that ensures the use of only one instance of a class (1 object - 1 class).
Avoid re-create instance
Problems
Addressing two issues at once:
Ensure that a class has just a single instance
- Manages the number of instances created in the system to control resource sharing within the system.
- Instead of creating a new instance every time it's used, each access will retrieve the previously created instance.
Provide a global access point to that instance
- Since this pattern involves initializing the instance once and using it in multiple places, considering it as a global variable is not incorrect.
Solution
- Make the constructor a private function.
- Create a static function that acts as a creation function instead of the constructor.
Peseudocode
class Singleton {
public static instance: Singleton;
public variable: string;
private constructor() {
this.variable = "initialized";
}
public static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
const hello = Singleton.getInstance();
const hi = Singleton.getInstance();
console.log(hello.variable === hi.variable); // true
Example
class Database {
private static instance: Database;
private constructor() {}
public static getInstance(): Database {
if (!this.instance) {
this.instance = new Database();
}
return this.instance;
}
}
const db = Database.getInstance();
const db2 = Database.getInstance();
console.log(db === db2);
Applicability
- Use when you want a class to have only one instance in the system, such as: database, connector to a 3rd party.
- Use when you want to tightly control global variables, ensuring the entire system shares a single instance.
Pros | Cons |
---|---|
Ensures there is only a single instance of a class. | However, maintaining and debugging can be difficult in multi-threaded scenarios. |
The object is created only on the first access. | This may violate the single responsibility principle. |
It is challenging to write unit tests for client code. |