Skip to content

Design Patterns

This module contains base classes or wrappers for creating Python design patterns easily.

Singleton

Create a class inheriting from SingletonBase, and that's it.

from backend_dev_utils import SingletonBase


class MyClass(SingletonBase):
    def __init__(self, value):
        self.value = value


obj1 = MyClass(10)
obj2 = MyClass(20)

print(obj1.value)  # Output: 10
print(obj2.value)  # Output: 10
print(obj1 is obj2)  # Output: True

NamedSingleton

Create a class inheriting from NamedSingletonBase and its first argument should always be name, which is a string. Then when you call this class with name instance1 let's say, and if you have never called it with the name instance1, then the instance will be created. Otherwise, you will get the instance created when you called the class with that name before.

from backend_dev_utils import NamedSingletonBase


class TestClass(NamedSingletonBase):
    def __init__(self, name: str, value: int) -> None:
        self.name = name
        self.value = value


obj1 = TestClass("instance1", 10)
obj2 = TestClass("instance1", 20)
obj3 = TestClass("instance2", 30)

print(obj1.name, obj1.value)  # Output: instance1 10
print(obj2.name, obj2.value)  # Output: instance1 10
print(obj3.name, obj3.value)  # Output: instance2 30
print(obj1 is obj2)  # Output: True
print(obj1 is obj3)  # Output: False