Python Singleton Design Pattern with Example

1. Definition

The Singleton Design Pattern ensures that a class has only one instance and provides a point of access to this instance from any other object in the system.

2. Problem Statement

Imagine a scenario where you need to ensure that a class has only one instance throughout the life cycle of an application, and you want to provide a global point to access that instance. Creating multiple instances of such a class could lead to unexpected behaviors or increased resource usage.

3. Solution

The Singleton Pattern restricts the instantiation of a class to one single instance and provides a way to access that instance. This is usually achieved by creating a static method in the class which returns the instance.

4. Real-World Use Cases

1. Database connection pools to restrict and reuse the number of connections.

2. Logging frameworks where a single instance handles writing logs from various parts of an application.

3. Configuration managers that hold application configurations and settings.

5. Implementation Steps

1. Declare the class's constructor as private.

2. Create a static variable in the class to hold the instance.

3. Create a static method that returns the instance, creating it if it doesn't already exist.

6. Implementation in Python

class Singleton:
    _instance = None  # Step 2: Static variable to hold the instance
    def __new__(cls):
        if not cls._instance:  # Check if the instance exists
            cls._instance = super(Singleton, cls).__new__(cls)  # Step 3: Create instance if it doesn't exist
        return cls._instance
# Test the Singleton
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 == singleton2)  # Should print True

Output:

True

Explanation:

1. We define a class Singleton and declare a private static variable _instance to hold the instance of the class.

2. We override the __new__ method which is responsible for creating instances in Python. Inside this method, we check if _instance is already defined.

3. If _instance is not defined, we call the superclass's __new__ method to create an instance. Otherwise, we return the existing instance.

4. In the test, we create two objects singleton1 and singleton2. Despite creating two objects, both point to the same memory location, ensuring that only one instance of the Singleton class exists.

7. When to use?

Use the Singleton Pattern when:

1. You want to ensure that a class has only one instance.

2. You need to provide a global point of access to the instance.

3. When controlling concurrent access to shared resources, ensure that resources like configuration are accessed in a synchronized manner.


Comments