python - Define number of uses in a decorator (Singleton pattern with decorators)
问题描述
I'm trying to implement a Singleton design pattern with using decorators. It can be easily achieved using metaclasses but the problem I've faced with is that a class can have more than 1 pattern.
For example, a class can be both an observer or a singleton. My decorator looks like this:
def Singleton(_cls):
_instances = {}
def wrapper(*args, **kwargs):
if _cls not in _instances:
_instances[_cls] = object.__new__(_cls)
_instances[_cls].__dict__.update(kwargs)
else:
raise AlreadyDefinedError(
"A Singleton instance has been defined already. "
"You can't have more than 1 Singleton object."
)
return _instances[_cls]
return wrapper
The problem is, since Singleton
is a function, this code doesn't work for it. Every time I decorate a new class, my _instances
dict
is re-defined and it's empty. Are there any ways of solving this problem?
解决方案
你还没有更新*args
你的字典。
有很多方法可以做一个单例装饰器。这是一种功能属性方法。
import functools as ft
def singleton(cls):
@ft.wraps(cls)
def wrapper(*args, **kwargs):
if wrapper.instance is None:
wrapper.instance = cls(*args, **kwargs)
return wrapper.instance
wrapper.instance = None
return wrapper
推荐阅读
- c# - 在视图中搜索日期 - ASP NET MVC
- python - 在 3D numpy 数组中查找第一次超过 2D 数组值的位置
- javascript - 我收到此错误 - 无法在“节点”上执行“appendChild”:参数 1 不是“节点”类型
- javascript - Firebase 函数 - 写入数据库
- javascript - 以附件形式发送 PDF 表单时是否可以格式化电子邮件正文?
- c# - .net 核心 2.1.3 ssl 错误
- hex - 在 Windows 中通过 ascii 或 hex 阻止数据包
- android - 如何在转换后重置 onClick 侦听器
- javascript - 此处带有数据 ID 的 onclick 有任何错误吗?
- mysql - 使 LEAST() 函数返回一个非空值