【Python基础知识库】Python单例模式

    技术2024-12-30  17

    单例模式

    使用__new__方法 class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a = 1 共享属性

    创建实例时把所有实例的__dict__指向同一个字典,这样它们具有相同的属性和方法.

    class Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return ob class MyClass2(Borg): a = 1 装饰器版本 def singleton(cls): instances = {} def getinstance(*args, **kw): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return getinstance @singleton class MyClass: ··· import方法

    作为python的模块是天然的单例模式

    # mysingleton.py class My_Singleton(object): def foo(self): pass my_singleton = My_Singleton() # to use from mysingleton import my_singleton my_singleton.foo() 元类实现单例 # 通过__init__方法实现元类(优雅) class Singleton(type): def __init__(self, *args, **kwargs): print("__init__") self.__instance = None super(Singleton, self).__init__(*args, **kwargs) def __call__(self, *args, **kwargs): print("__call__") if self.__instance is None: self.__instance = super(Singleton, self).__call__(*args, **kwargs) return self.__instance class Foo(metaclass=Singleton): __metaclass__ = Singleton foo1 = Foo() foo2 = Foo() print(Foo.__dict__) print(foo1 is foo2) # 通过元类的__new__方法实现元类(为了实例增加属性重写__new__方法,不推荐) class Singleton(type): def __new__(cls, name, bases, attrs): print("__new__") attrs["_instance"] = None return super(Singleton, cls).__new__(cls, name, bases, attrs) def __call__(self, *args, **kwargs): print("__call__") if self._instance is None: self._instance = super(Singleton, self).__call__(*args, **kwargs) return self._instance class Foo(metaclass=Singleton): __metaclass__ = Singleton foo1 = Foo() foo2 = Foo() print(Foo.__dict__) print(foo1 is foo2)

    单例模式伯乐在线详细解释

    Processed: 0.010, SQL: 12