Python实现单例模式的5种方式
写在前面
学究嘛,就记录一下;
本质都是通过设置一个标志位来实现, 通俗的讲就是当第一次实例化时, 记录下"已经实例化了", 当再次实例化时, 将"记录"的地址返回;
题外话, 函数它不香么? 还面向对象, 要什么对象.
1. 模块(module)
这种方式不用干啥, 正常写code就可以了, 一旦这个模块被导入就会生成.pyc文件, 第二次导入时加载的就是.pyc
# girl.pyclass GirlFriend: passLucy = GirlFriend()# me.pyfrom girl import Lucy
2. 装饰器实现
定义一个装饰器如下
def singleton(cls): instances = {} @functools.wraps(cls) def _wrapper(*args, **kw): if cls not in instances: print('没有该实例,创建一个') instances[cls] = cls(*args, **kw) return instances[cls] return _wrapper
使用装饰器
@singletonclass GirlFriend: pass
3. 类
装饰器使其
class Singleton: def __init__(self, cls): self._cls = cls self._instance = {} def __call__(self, *args): if self._cls not in self._instance: self._instance[self._cls] = self._cls(*args) return self._instance[self._cls]# 用法@Singletonclass GirlFriend: pass
4. __new__
方法实现
class GirlFriend: def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): cls._instance = super().__new__(cls) return cls._instance# 用法Lucy = GirlFriend()
5. 元类实现
class GirlFriend(type): def __new__(cls, name, bases, attrs): cls._instance = None return type.__new__(cls, name, bases, attrs) def __call__(cls, *args, **kw): if cls._instance is None: cls._instance = type.__call__(cls, *args, **kw) return cls._instance# 用法class Lucy(metaclass=GirlFriend): pass
总结
- 装饰器实现比较简单, 也好理解
赞 (0)