Singleton Pattern: What It Is and How It Works
Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to it. It is used to control access to shared resources or services in an application.How It Works
The Singleton pattern works by making sure that only one object of a class can ever be created. Imagine a company where only one CEO is allowed. No matter how many departments or employees there are, there is always just one CEO. Similarly, the Singleton pattern restricts the creation of multiple instances.
It does this by hiding the class constructor and providing a special method that returns the single instance. If the instance does not exist yet, it creates it; if it already exists, it returns the existing one. This way, all parts of the program use the same object, avoiding conflicts or duplicated data.
Example
This example shows a simple Singleton class in Python. The __new__ method ensures only one instance is created and reused.
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.value = 0 return cls._instance # Usage obj1 = Singleton() obj2 = Singleton() obj1.value = 42 print(f"obj2.value: {obj2.value}") # Shows 42 because obj1 and obj2 are the same instance
When to Use
Use the Singleton pattern when you need to control access to a shared resource, such as a database connection, configuration settings, or a logging service. It ensures that all parts of your program use the same instance, preventing inconsistent states or duplicated work.
For example, in a game, you might want only one instance of the game manager to keep track of the score and game state. In web applications, a single cache manager instance can improve performance and consistency.
Key Points
- Singleton restricts a class to one instance.
- It provides a global access point to that instance.
- Useful for shared resources like configuration or logging.
- Helps avoid conflicts from multiple instances.