Sobes.tech
Middle+

Design patterns and implementation of Singleton.

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. This is useful when you need to centrally manage resources, such as configurations or database connections.

Example of implementing Singleton in Python:

class Singleton:
    _instance = None

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

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

In a multithreaded environment, thread safety must be ensured, for example, using locks. In other languages (Java, C#), Singleton is often implemented using static methods and lazy initialization.

Design patterns and implementation of Singleton. — QA… - sobes.tech