Sobes.tech
Middle

What do you know 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 it.

It is used when:

  • Managing access to a resource (e.g., database, file system).
  • Only one instance of a specific type of object is needed in the system.

Implementation in Python can be based on:

  • The __new__ method: Override __new__ to always return the same instance.

    class Singleton:
        _instance = None
    
        def __new__(cls):
            if cls._instance is None:
                cls._instance = super().__new__(cls)
            return cls._instance
    
  • Class decorator: Create a decorator function that manages instance creation.

    def singleton(cls):
        instances = {}
    
        def get_instance(*args, **kwargs):
            if cls not in instances:
                instances[cls] = cls(*args, **kwargs)
            return instances[cls]
    
        return get_instance
    
    @singleton
    class MySingleton:
        def __init__(self, value):
            self.value = value
    
  • Module: Python imports modules only once, which can be used to create a singleton.

    # singleton_module.py
    class MySingleton:
        pass # Class definition
    
    instance = MySingleton() # Create a single instance
    

    Then import with from singleton_module import instance.

Advantages:

  • Controlled access to the single instance.
  • Resource savings when working with heavy objects.

Disadvantages:

  • Can complicate testing (due to global state).
  • Violates the single responsibility principle.
  • In multithreaded environments, synchronization is required for safe initialization.