Sobes.tech
Middle

Can you tell me about the Singleton pattern?

sobes.tech AI

Answer from AI

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

In Python, Singleton can be implemented in several ways. One simple way is to use a module, as modules in Python are essentially singletons. But if a class is needed, you can do it like this:

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

This code ensures that when multiple objects of the Singleton class are created, the same instance is returned.