首页 > 代码库 > Python设计模式之单例模式
Python设计模式之单例模式
单例模式
- 如何保证创建的实例是唯一的
- 如何保证多线程情况下的访问
- 清晰明了
- module
- metaclass
- __new__
- decorator
module
- 首先在一个py文件中定义这么一个单例类:
class Singleton(object): def __init__(self): self._val = 10 @property def val(self): return self._val @val.setter def val(self, val): self._val = val singleton = Singleton()
- 然后再在其它的文件中import
from Singleton import singleton assert singleton.val == 10 singleton.val = 20 assert singleton.val == 20
metaclass
class Singleton(type): def __init__(cls, what, bases, dict): super().__init__(what, bases, dict) cls._instance = None def __call__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__call__(*args, **kwargs) return cls._instance class MyClass(metaclass=Singleton): pass class1 = MyClass() class2 = MyClass() assert class1 == class2
__call__
class Singleton(object): _instance = None def __new__(cls, *more): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *more) return cls._instance class MyClass(Singleton): pass class1 = MyClass() class2 = MyClass() assert id(class1) == id(class2)
装饰器
import functools def singleton(cls): cls.__new_original__ = cls.__new__ @functools.wraps(cls.__new__) def singleton_new(cls, *args, **kw): it = cls.__dict__.get(‘__it__‘) if it is not None: return it cls.__it__ = it = cls.__new_original__(cls, *args, **kw) it.__init_original__(*args, **kw) return it cls.__new__ = singleton_new cls.__init_original__ = cls.__init__ cls.__init__ = object.__init__ return cls @singleton class myclass: pass class1 = myclass() class2 = myclass() assert class1 == class2
Python设计模式之单例模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。