Junior
What is a singleton?
sobes.tech AI
Answer from AI
Singleton is a creational design pattern that guarantees a class has only one instance and provides a global point of access to that instance.
Main ideas:
- Single instance: Prevents creating more than one instance of the class.
- Global access: Provides a static method or property that returns the single instance.
Applications:
- Managing access to resources (e.g., database access, application settings).
- Logging.
- Caching.
Example implementation in JavaScript:
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance; // Return existing instance
}
this.data = 'Some data'; // Initialize instance
Singleton.instance = this; // Save new instance
return this;
}
getData() {
return this.data;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton(); // Create instance if it doesn't exist
}
return Singleton.instance; // Return existing or new instance
}
}
// Usage
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
// instance1 and instance2 refer to the same object
console.log(instance1 === instance2); // true
Advantages:
- Controlled access to the single instance.
- Resource savings when working with objects that are costly to create.
Disadvantages:
- Can make testing difficult, as the singleton's state can affect different parts of the application.
- May violate the single responsibility principle if the singleton handles too many things.
- In multithreaded environments, special care is required to ensure thread safety.