当前位置:首页 > 编程笔记 > 正文
已解决

Python单例模式(3种常用方式)

来自网友在路上 162862提问 提问时间:2023-09-29 16:35:14阅读次数: 62

最佳答案 问答题库628位专家为你答疑解惑

Python单例模式

    • 1、使用模块(推荐)
    • 2、使用装饰器
    • 3、使用new()方法


单例模式是最常见的一种设计模式,该模式确保系统中一个类有且仅有一个实例

常用的三种实现方式如下:

1、使用模块(推荐)


模块是天然单例的,因为模块只会被加载一次,加载后,其他脚本若导入使用时,会从sys.modules中找到已加载好的模块,多线程下也是如此

编写Singleton.py脚本:

class MySingleton():def __init__(self, name, age):self.name = nameself.age = age

其他脚本导入使用:

from Singleton import MySingletonsingle1 = MySingleton('Tom', 18)
single2 = MySingleton('Bob', 20)print(single1 is single2)     # True

2、使用装饰器


可以通过装饰器装饰需要支持单例的类

from threading import RLockdef Singleton(cls):single_lock = RLock()instance = {}def singleton_wrapper(*args, **kwargs):with single_lock:if cls not in instance:instance[cls] = cls(*args, **kwargs)return instance[cls]return singleton_wrapper@Singleton
class MySingleton(object):def __init__(self, name, age):self.name = nameself.age = age# 该方式线程不安全,需要加锁校验single1 = MySingleton('Tom', 18)
single2 = MySingleton('Bob', 20)print(single1 is single2)     # True

3、使用new()方法


Python的__new__()方法是用来创建实例的,可以在其创建实例的时候进行控制

class MySingleton(object):single_lock = RLock()def __init__(self, name, age):self.name = nameself.age = agedef __new__(cls, *args, **kwargs):with MySingleton.single_lock:if not hasattr(MySingleton, '_instance'):MySingleton._instance = object.__new__(cls)return MySingleton._instancesingle1 = MySingleton('Tom', 18)
single2 = MySingleton('Bob', 20)print(single1 is single2)     # True
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Python单例模式(3种常用方式)":http://eshow365.cn/6-15461-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!