个人总结
command.py
file.py
time.py
excel.py
with 的原理和用法
subprocess 模块
cline 提示词
PathLike
pathlib
peewee
生成随机ID
FastApi 使用 peewee
http connect
Dataframe Protocol
pyarrow
overload 函数重载
1111
peewee 线程安全
Python 日志模块
rabbitmq 问答
多进程 daemon 参数
记录异常
dict.py
多进程
忽略异常
timer.py
Ctrl+C 退出while
发布pip包
Bolo组件
迭代器与生成器
dataclass
单例模式(二)
单例模式(一)
errors.py
enum.py
每日学习
本文档使用 MrDoc 发布
-
+
首页
单例模式(一)
### 1. 通过模块导入 ``` from student import student ``` ### 2. 使用new方法 ``` class Student: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance def __init__(self, name, age): print("init") self.name = name self.age = age s = Student("xiaoming01", 15) s = Student("xiaoming02", 16) ``` 但是这个方法有个问题,就是每次获取实例的时候都会执行初始化方法`__init__` ### 3. 使用函数装饰器 ``` def singleton(cls): instances = {} def _singleton(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return _singleton @singleton class Student2(object): def __init__(self, name, age): print("init") self.name = name self.age = age ``` 这个方法比较好一点,初始化方法只会执行一次。 但是这个方法容易导致内存的增长,要注意清理`instances`存储的对象。 ### 4. 使用类的装饰器 ``` class SingleTon: _instances = {} def __init__(self, cls_name): self.cls_name = cls_name def __call__(self, *args, **kwargs): if self.cls_name not in SingleTon._instances: SingleTon._instances[self.cls_name] = self.cls_name(*args, **kwargs) return SingleTon._instances.get(self.cls_name) @SingleTon class Student2(object): def __init__(self, name, age): print("init") self.name = name self.age = age ``` 类的装饰器和函数装饰器的效果是一样的 ### 5. 使用函数来创建对象 ``` _instances = {} def create_student(name, age): key = f"{name}_{age}" if key in _instances: return _instances[key] stu = Student(name, age) _instances[key] = stu return stu ``` 这种方法其实跟函数装饰器是一样的,装饰器算隐式调用,这个算显示调用 ### 参考 > [6 种方法实现单例模式](https://www.cnblogs.com/wozijisun/p/16635365.html)
gaojian
2022年12月14日 16:21
分享文档
收藏文档
上一篇
下一篇
微信扫一扫
复制链接
手机扫一扫进行分享
复制链接
关于 MrDoc
觅思文档MrDoc
是
州的先生
开发并开源的在线文档系统,其适合作为个人和小型团队的云笔记、文档和知识库管理工具。
如果觅思文档给你或你的团队带来了帮助,欢迎对作者进行一些打赏捐助,这将有力支持作者持续投入精力更新和维护觅思文档,感谢你的捐助!
>>>捐助鸣谢列表
微信
支付宝
QQ
PayPal
Markdown文件
分享
链接
类型
密码
更新密码