Python 中单例模式 4种方法
2024-08-27 11:28:04
假设我们在一个与数据库交互的系统中,需要进行数据库操作,那么我们就有必要了解单例模式,单例模式使得我们不用每次进行数据库的操作时都去链接数据库。
我将循环渐进,由浅入深的写一下单例模式示例。
实例1:
db.py
class Foo(object): def __init__(self): self.conn = "连接数据库" def get(self): return self.conn obj = Foo()
views.py
import db print(db.obj)
run.py
import db import views print(db.obj)
执行run.py,打印结果如下,这就是单例模式
<db.Foo object at 0x000001C1D8FC5A58> <db.Foo object at 0x000001C1D8FC5A58>
实例二:
注意这里使用了锁来解决线程安全问题
import threading import time class Foo(object): instance = None lock = threading.Lock() def __init__(self): self.a1 = 1 self.a2 = 2 import time import random time.sleep(2) @classmethod def get_instance(cls,*args,**kwargs): if not cls.instance: with cls.lock: if not cls.instance: obj = cls(*args,**kwargs) cls.instance = obj return cls.instance return cls.instance def task(): obj = Foo.get_instance() print(obj) import threading for i in range(5): t = threading.Thread(target=task,) t.start() time.sleep(10) Foo.get_instance()
实例三:
import threading class Foo(object): instance = None lock = threading.Lock() def __init__(self): self.a1 = 1 self.a2 = 2 import time time.sleep(2) def __new__(cls, *args, **kwargs): if not cls.instance: with cls.lock: if not cls.instance: obj = super(Foo, cls).__new__(cls, *args, **kwargs) cls.instance = obj return cls.instance return cls.instance def task(): obj = Foo() print(obj) import threading for i in range(5): t = threading.Thread(target=task, ) t.start()
实例四:
import threading lock = threading.Lock() class Singleton(type): def __call__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): with lock: if not hasattr(cls, 'instance'): obj = cls.__new__(cls, *args, **kwargs) obj.__init__(*args, **kwargs) setattr(cls, 'instance', obj) return getattr(cls, 'instance') return getattr(cls, 'instance') class Foo(object, metaclass=Singleton): def __init__(self): self.name = 'alex' obj1 = Foo() obj2 = Foo() print(obj1, obj2)
最新文章
- stm32新建工程详细步骤
- SQL Server删除重复行的6个方法
- 【OSG】osgText::Text 研究
- hdu 1087
- preventDefault() 方法 取消掉与事件关联的默认动作
- poj 2104 K-th Number - 经典划分树
- Problem 2169 shadow
- C#_会员管理系统:开发二(会员资料管理界面的‘增删改查’)
- Unity3D方法来隐藏和显示对象
- Linux shell 脚本(一)
- List GroupBy真实用法,Reflection(反射)用法,Enum用法,正则,搜索下拉布局
- 第一篇-Win10打开txt文件出现中文乱码
- 【Jmeter】api性能测试总结
- Metasploit 简单渗透应用
- JavaScript 第七章总结
- prime docker-compose 环境运行试用
- 【树】Construct Binary Tree from Preorder and Inorder Traversal
- 【Android】3.5 示例5--多地图展示
- 自创open vp n windows步骤
- Netty框架
热门文章
- 20145204 《Java程序设计》第9周学习总结
- 学习Zookeeper之第2章Zookeeper安装
- Python学习札记(二十二) 函数式编程3 filter &; SyntaxError: unexpected EOF while parsing
- UVa 10534 波浪子序列(快速求LIS)
- hdu 1004 Let the Balloon Rise strcmp、map、trie树
- Codeforces 909C Python Indentation:树状数组优化dp
- 一个产生临时图片Url的地方
- Python小工具之消耗系统指定大小内存
- 深入理解javascript之typeof和instanceof
- URAL 1106 Two Teams (DFS)