Sobes.tech
Middle+

Tell me about Singleton — what is it and how is it implemented?

sobes.tech AI

Answer from AI

Singleton is a design pattern that guarantees a class has only one instance and provides a global point of access to it.

In Python, it can be implemented in several ways. One simple way is to use a class with a private instance attribute and a class method for access:

class Singleton:
    _instance = None

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

# Usage
s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # True

Thus, when creating a new object, it checks whether an instance already exists, and if so, it returns that instance.

Tell me about Singleton — what is it and how is it… - sobes.tech