23. Singleton Pattern

The Singleton Pattern ensures that a class has only one instance throughout the application's lifetime and provides a global point of access to that instance.

1. Classic Singleton using a Private Class Variable

Copy

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)  # True

2. Singleton with Initialization

Copy

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
            cls._initialized = False
        return cls._instance

    def __init__(self, value):
        if not self._initialized:
            self.value = value
            self._initialized = True

obj1 = Singleton(10)
obj2 = Singleton(20)
print(obj1 is obj2)  # True
print(obj1.value)    # 10
print(obj2.value)    # 10

3. Singleton Using a Decorator

Copy


4. Singleton Using a Metaclass

Copy


5. Thread-Safe Singleton

Copy


6. Singleton with Global Instance

Copy


7. Singleton Using a Module

Copy


8. Singleton with Weak References

Copy


9. Singleton Using Borg Pattern (Shared State)

Copy


10. Config Manager Singleton Example

Copy


These examples demonstrate various ways to implement the Singleton Pattern in Python, providing flexibility for different use cases such as thread safety, module-level singletons, and shared state.

Last updated