Junior — Middle
Can you explain the principle of the Singleton pattern and where it is usually used?
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 it.
This is useful when you need to control access to a resource, such as a database, logger, or configuration.
Example of implementing Singleton in Python:
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
Singletons are typically used for objects that should be unique within an application to avoid conflicts and resource overuse.