- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
In software design, some objects are meant to be shared across the entire application. Think of a configuration manager, a database connection, or a logger. You don’t want to create multiple instances of these — just one that is reused everywhere. That’s exactly where the Singleton Pattern comes in.
? What is the Singleton Pattern?
The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it.
It’s part of the Creational Design Patterns — patterns focused on object creation.
? Real-Life Analogy
Think of a government. There’s only one Prime Minister (ideally ?). If you try to create a new one, it should refer to the existing one.
? Use Cases
- Database connections
- Logging services
- Config/environment managers
- Thread pools
- Caching mechanisms
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this.timestamp = new Date();
Singleton.instance = this;
}
getTime() {
return this.timestamp;
}
}
// Usage
const a = new Singleton();
const b = new Singleton();
console.log(a === b); // true
console.log(a.getTime() === b.getTime()); // true
? Example in Python
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
cls._instance.timestamp = "Created at instance creation"
return cls._instance
# Usage
a = Singleton()
b = Singleton()
print(a is b) # True
- Controlled access to a single instance
- Saves memory (especially useful for expensive objects)
- Can be lazily loaded (created only when needed)
- Global state can be hard to test
- Can violate Single Responsibility Principle
- In multithreading environments, needs proper locking (especially in Java/C++)
- Keep it stateless if possible
- Avoid abusing it like a global variable
- Be cautious in multi-threaded apps (use locks/mutexes)
- The Singleton Pattern is a handy tool when you need exactly one instance of a class to coordinate actions across the system. Use it wisely and you’ll make your application more efficient and structured.