Several methods to achieve single-mode embodiment

Singleton

Singleton (Singleton Pattern) is a common software design pattern, the main purpose of this mode is to ensure that a certain class has only one instance exists . When you want in the whole system, can appear only one instance of a class, singleton objects can come in handy.

For example, a server program configuration information stored in a file, the client configuration file to read information through a AppConfig class. If the program is running, there is a lot of need to use the contents of the configuration file, that is to say, a lot of places need to create an instance of an object AppConfig, which led to multiple instances of objects AppConfig system, but this is a serious waste of memory resources, especially in many cases the configuration file content. In fact, like this class AppConfig, we hope that there is only one instance of the object during the program run.

In Python, we can use a variety of methods to achieve single-mode embodiment

Are implemented using modules singleton

In fact, Python module is a natural Singleton pattern , because the module at the time of the first import, will generate  .pyc files when importing the second time, it will be loaded directly  .pyc file without execution module code again. Thus, we only need to define the data and related functions in one module, it is possible to obtain a single embodiment of the subject. If we really want a singleton class, you can consider doing so:

mysingleton.py

class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()

The above code is stored in a file  mysingleton.py in use is to be introduced into the object file directly in other files, the object that is the object of the singleton

  from a import singleton

Example decorator single-mode

def Singleton(cls):
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton


@Singleton
class A(object):
    a = 1

    def __init__(self, x=0):
        self.x = x


a1 = A(2)  

Use __new__ method

class Person:
    from therading import Lock
    lock = Lock()
    _instance = None
    def __new__(cls,*args,**kwargs):
    with  cls.lock:
    
            if cls._instance is None:
                cls._instance =  object.__new__(cls)
            return cls._instance
    def __init__(self):
        pass

  

Guess you like

Origin www.cnblogs.com/xinjie123/p/10957190.html