One example design pattern of Python version

Singleton mode

In some scenarios, we want entity classes to generate only one entity object no matter how many instances they are instantiated. In this case, we need to use singleton mode. The commonly used scenario is the global configuration class.

Schema framework

  • Mode 1: use the decorator
"""Using functions to define decorators"""
def singletons(cls):
    """
    //Define a single case decorator. Use dict to save the defined entity. The key is the address of the class instead of the name, so that the class with the same name will not conflict
    """
    instances = {}

    def wrapper(*args, **kwargs):
        if cls not in instances.keys():
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return wrapper
"""Using classes to define decorators"""
class singletons(object):
    instances = {}

    def __init__(self, cls):
        self.__cls = cls

    def __call__(self, *args, **kwargs):
        if self.__cls not in singletons.instances.keys():
            singletons.instances[self.__cls] = self.__cls(*args, **kwargs)
        return singletons.instances[self.__cls]
  • Mode 2: override the new method, which is only valid for the currently modified class
class SingletonTest(object):

    __instance = None
    __isFirstInit = False

    def __new__(cls, name):
        if not cls.__instance:
            SingletonTest.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self, name):
        if not self.__isFirstInit:
            self.__name = name
            SingletonTest.__isFirstInit = True

    def getName(self):
        return self.__name

UML diagram

Example

@singletons
class Test(object):
    def __init__(self, name):
        self.__name = name

    def hello(self):
        print("I am {} object {}".format(self.__name, id(self)))


if __name__ == "__main__":
    test1 = Test("test1")
    test2 = Test("test2")
    test1.hello()
    test2.hello()
'''Test output'''
# I am test1 object 2453169112512
# I am test1 object 2453169112512

Extended thinking

  1. Thread safety in singleton mode.

Tags: Python

Posted on Mon, 02 Dec 2019 11:17:17 -0800 by gukii