概念:
一个对象只能最多存在一个实例
优点:
节省资源空间
缺点:
多线程失效,需要加锁解决
两种实现方式:
需要用到的知识点
1.单例模式思想
2.装饰器
3.类对象
4.__new__方法
4.with语句
5.多线程资源竞争使单例模式失效,导致脏读,使用锁解决
# 方式1:装饰器实现 非线程安全
def singleton(cls):
_instances = {}
def wrapper(*args, **kwargs):
if cls not in _instances:
_instances[cls] = cls(*args, **kwargs)
return _instances[cls]
return wrapper
@singleton
class ConfigManager:
def __init__(self):
self.settings = {}
# 方式1:装饰器实现 线程安全
import threading
def singleton(cls):
__instances = {}
__lock = threading.Lock()
def wrapper(*args, **kwargs):
with __lock:
if cls not in _instances:
_instances[cls] = cls(*args, **kwargs)
return _instances[cls]
return wrapper
@singleton
class ConfigManager:
def __init__(self):
self.settings = {}
# 方式2:__new__方法重写 重点++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class CacheManager:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
cls._instance._cache = {}
return cls._instance
# 方式2:线程安全版(带锁)
from threading import Lock
class ThreadSafeSingleton:
_instance = None
_lock = Lock()
def __new__(cls):
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
方式3:
所有模块导入的类也是默认单例
1万+

被折叠的 条评论
为什么被折叠?



