单例模式
Posted liuwei0824
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
Method 1: A decorator
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass
Method 2: A base class
class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton, BaseClass): pass
Method 3: A metaclass
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] #Python2 class MyClass(BaseClass): __metaclass__ = Singleton #Python3 class MyClass(BaseClass, metaclass=Singleton): pass
Method 4: decorator returning a class with the same name
def singleton(class_): class class_w(class_): _instance = None def __new__(class_, *args, **kwargs): if class_w._instance is None: class_w._instance = super(class_w, class_).__new__(class_, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs): if self._sealed: return super(class_w, self).__init__(*args, **kwargs) self._sealed = True class_w.__name__ = class_.__name__ return class_w @singleton class MyClass(BaseClass): pass
支持多线程:
import time import threading def singleton(class_): class class_w(class_): _instance_lock = threading.Lock() _instance = None def __new__(class_, *args, **kwargs): if class_w._instance is None: # time.sleep(2) with class_w._instance_lock: if class_w._instance is None: class_w._instance = super(class_w, class_).__new__(class_, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs): if self._sealed: return super(class_w, self).__init__(*args, **kwargs) self._sealed = True class_w.__name__ = class_.__name__ return class_w class BaseClass(object): pass @singleton class MyClass(BaseClass): pass if __name__ == ‘__main__‘: def task(arg): obj = MyClass() print(id(obj)) for i in range(10): t = threading.Thread(target=task, args=[i, ]) t.start() time.sleep(20) obj = MyClass() print(id(obj)) # for i in range(100): # my_obj = MyClass() # print(id(my_obj))
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章