Junior — Middle
Can you explain what is meant by the Singleton pattern in programming?
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it.
Main characteristics:
- The class constructor is private or protected to prevent instantiation from outside.
- The class contains a static method that returns the single instance.
- The instance is created either lazily upon first request or immediately.
Example in C++:
class Singleton {
private:
Singleton() {} // private constructor
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
public:
static Singleton& getInstance() {
static Singleton instance; // created once
return instance;
}
void doSomething() {
// ...
}
};
// Usage:
Singleton& s = Singleton::getInstance();
s.doSomething();
This pattern is useful when a single shared object is needed, for example, for managing configuration or resource access.