铜陵商城网站建设,网站的链接建设,做网站的 需要续费维护费吗,照片视频制作小程序Python单例模式 1、使用模块#xff08;推荐#xff09;2、使用装饰器3、使用new()方法 单例模式是最常见的一种设计模式#xff0c;该模式确保系统中一个类仅有一个实例
常用的三种实现方式如下#xff1a;
1、使用模块#xff08;推荐#xff09; 模块是天然单例的推荐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) # True2、使用装饰器
# 编写一个单例模式的装饰器来装饰哪些需要支持单例的类
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_wrapperSingleton
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) # True3、使用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