Singleton design pattern

class Singleton:
    instance = None

    def __new__(cls):
        if cls.instance is None:
            cls.instance = super().__new__(cls)
       
        return cls.instance

a = Singleton()
b = Singleton()

print(a is b)
# Output: True

The Singleton, or "Singleton" pattern, is a design pattern that describes an object that has a single, unique instance.

The __new__ method is called to create an instance of a class, before the __init__ method. The method takes the class itself as its first argument and should return an instance (which can even be an instance of another class).

In the example, we check whether the instance attribute has a value. If not, we assign the attribute an instance of the same class. If an instance already exists, we simply return it.

Thus, when the constructor of the Singleton class is called, the same object from memory will be returned each time.

Comments (0)

Leave a comment