Design Pattern Implementer | Python

Singleton Design Pattern Implementation in Python

Understand a Python code snippet demonstrating the Singleton design pattern ensuring only one instance of a class is created and shared globally.


Empty image or helper icon

Prompt

class Singleton(type):
    _instances = {}
    
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class MyClass(metaclass=Singleton):
    pass

instance1 = MyClass()
instance2 = MyClass()

print(id(instance1) == id(instance2))

Answer

Design Pattern: Singleton Design Pattern

Problem Analysis:

  • The provided Python code snippet implements the Singleton design pattern.
  • Singleton ensures that a class has only one instance and provides a global point of access to that instance.

Code Template - Singleton Design Pattern Implementation (Python):

class Singleton(type):
    _instances = {}
    
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class MyClass(metaclass=Singleton):
    pass

instance1 = MyClass()
instance2 = MyClass()

print(id(instance1) == id(instance2))  # Output: True

Implementation Details:

  1. Singleton Class: Defines a metaclass Singleton that tracks instances of its subclasses using a dictionary _instances.
  2. call Method: Overrides the __call__ method to ensure only one instance of each class is created and returned.
  3. MyClass Definition: Inherits from Singleton metaclass to enforce the Singleton pattern.
  4. Instance Creation: instance1 and instance2 are instances of MyClass.
  5. Instance Comparison: print(id(instance1) == id(instance2)) compares the identities of two instances, returning True if they are the same instance.

Code Explanation:

  • The Singleton design pattern restricts the instantiation of a class to a single instance and provides a way to access that instance globally.
  • The metaclass Singleton keeps track of instances for each class and ensures that only one instance is created.
  • By using the metaclass Singleton, the class MyClass becomes a Singleton class with only one instance created.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

Understand a Python code snippet demonstrating the Singleton design pattern ensuring only one instance of a class is created and shared globally.