Python Singleton(单例模式)实现
来源:互联网 发布:高分三号卫星数据下载 编辑:程序博客网 时间:2024/04/27 18:45
1. 重载__new__方法
class Singleton(object): def __new__(cls, *args, **kwargs): ''' A pythonic singleton ''' if '_inst' not in vars(cls): cls._inst = super().__new__(cls, *args, **kwargs) return cls._inst def __init__(self, *args, **kwargs): pass
2. 使用装饰器
class SingletonDecorator(object): def __init__(self, cls): self._cls = cls self._inst = None def __call__(self, *args, **kwargs): ''' Over __call__ method. So the instance of this class can be called as a function. ''' if not self._inst: self._inst = self._cls(*args, **kwargs) return self._instclass DemoCls(object): passDemoCls = SingletonDecorator(DemoCls)# After this the DemoCls is bind with a SingletonDecorator instancea = DemoCls()b = DemoCls()
3. 利用python管理module的机制
import sysclass MyCls(object): def __init__(self, *args, **kwargs): passsys.modules[__name__] = MyCls()# After this statement, the test module is bind with a MyCls instance# If you import this module in other module,# test is a MyCls instance actually.
4. share instance property
共享 __dict__ 即可。
- Python Singleton(单例模式)实现
- Python Singleton(单例模式)实现
- python Singleton单例模式实现
- 实现Singleton模式( 单例模式)
- Python - 单例模式(Singleton)
- python单例模式Singleton
- Java 实现单例(Singleton)模式
- 【JAVA实现】单例模式(singleton)
- 实现Singleton(单例)模式.
- 设计模式系列Python实现(一)-单例模式(Singleton)
- Python实现设计模式--01.单例模式(Singleton Pattern)
- 设计模式实现(十七)---单例模式(SingleTon)
- 设计模式 - 单例模式(Singleton) C++实现
- 设计模式C++实现:单例模式(Singleton)
- singleton模式 (单例模式C++实现)
- Python - 单例模式(Singleton)(转)
- Python中的Singleton (单件)模式
- Python和Singleton (单件)模式
- 英语单词的重要前缀
- PlayBook最常被问到的5个问题
- LTE PDCCH忙检测,并补充
- php之无限极分类
- 杭电Hd 2024 C语言合法标识符
- Python Singleton(单例模式)实现
- 我的CSDN情结之年度总结
- how iOS rotation works
- 2 总结一下常用web.config公共配置。
- TClientDataSet[22]: 数组字段与 ObjectView
- 黑马程序员-线程Thread学习笔记
- Ubuntu发布移动版操作系统
- LTE下行调度算法概述
- memset函数使用详解