| 什么是单例模式?单例模式是指:保证一个类仅有一个实例,并提供一个访问它的全局访问点 |
| |
| cursor.excute('select * from user') |
| |
| |
| cursor.excute('select * from books') |
| |
| |
| cursor.fetchAll() |
| |
| |
1.使用模块
其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc
文件,当第二次导入时,就会直接加载 .pyc
文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:
mysingleton.py
| class Singleton(object): |
| def foo(self): |
| pass |
| singleton = Singleton() |
将上面的代码保存在文件 mysingleton.py
中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象
2.使用装饰器
| def Singleton(cls): |
| instance = None |
| |
| def _singleton(*args, **kargs): |
| nonlocal instance |
| if instance is None: |
| instance = cls(*args, **kargs) |
| return instance |
| |
| return _singleton |
| |
| |
| @Singleton |
| class A(object): |
| def __init__(self, x=0): |
| self.x = x |
| |
| |
| a1 = A(2) |
| a2 = A(3) |
| print(a1.x) |
| print(a2.x) |
| |
| print(a1 is a2) |
3.使用类方法
| class Singleton(object): |
| _instance=None |
| def __init__(self): |
| pass |
| |
| @classmethod |
| def instance(cls, *args, **kwargs): |
| if cls._instance is None: |
| cls._instance=cls(*args, **kwargs) |
| return cls._instance |
| |
| a1=Singleton.instance() |
| a2=Singleton().instance() |
| |
| print(a1 is a2) |
4.基于new方法实现
| class Singleton(object): |
| _instance=None |
| def __init__(self): |
| pass |
| |
| |
| def __new__(cls, *args, **kwargs): |
| if cls._instance is None: |
| cls._instance = object.__new__(cls) |
| return cls._instance |
| |
| obj1 = Singleton() |
| obj2 = Singleton() |
| print(obj1 is obj2) |
| class SingletonType(type): |
| _instance=None |
| def __call__(cls, *args, **kwargs): |
| if cls._instance is none: |
| |
| cls._instance = object.__new__(cls) |
| cls._instance.__init__(*args, **kwargs) |
| return cls._instance |
| |
| class Foo(metaclass=SingletonType): |
| def __init__(self,name): |
| self.name = name |
| |
| |
| obj1 = Foo('name') |
| obj2 = Foo('name') |
| print(obj1.name) |
| print(obj1 is obj2) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库