Create singleton class with a decorator in python

Create singleton class with a decorator in python

A singleton is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. In Python, you can implement a singleton pattern using a decorator. Here’s how you can create a singleton class using a decorator:

Python
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 SingletonClass:
    def __init__(self, value):
        self.value = value

    def show_value(self):
        print(self.value)

# Create instances of the singleton class
singleton_instance1 = SingletonClass("Instance 1")
singleton_instance2 = SingletonClass("Instance 2")

# Both instances point to the same object
singleton_instance1.show_value()  # Output: Instance 1
singleton_instance2.show_value()  # Output: Instance 1

In this example, the singleton decorator defines a dictionary called instances to store the instances of singleton classes. The get_instance function is returned by the decorator, and it checks if an instance of the class already exists. If not, it creates a new instance and stores it in the instances dictionary.

The SingletonClass is decorated with @singleton, which means that each time you create an instance of SingletonClass, it will always return the same instance.

Decorators offer a clean and convenient way to implement the singleton pattern and ensure that a class has only one instance throughout the program.

Total
0
Shares

Leave a Reply

Previous Post
Decorator with arguments in python

Decorator with arguments in python

Next Post
Using a decorator to time a function in python

Using a decorator to time a function in python

Related Posts