https://blog.csdn.net/weixin_45912307/article/details/115471720
# -- encoding: utf-8 --
# @time: 2021/4/5 18:42
# @Author: jsonLiu
# @Email: xxxxxxx@qq.com
# @file: singlepattern
"""
1、定义一个类属性,来记录该类是否创建过对象 instance = None
2、在_new_方法中对类属性做判断
- 2.1没有创建过对象。那就创建一个(保存起来),并且修改类属性的值
- 2.2创建过了,就将之前创建的返回出去
"""
# 1. 简单模式:一个类只有单个对象被创建
class MyClass(object):
__isinstance=None
def __new__(cls, *args, **kwargs):
if not cls.__isinstance:
cls.__isinstance = super().__new__(cls) # 方法1
# cls.__isinstance = object.__new__(cls) # 方法2
return cls.__isinstance
else:
return cls.__isinstance
t1 = MyClass()
t2 = MyClass()
print(t1 is t2) # True
# 2. 装饰器实现单例模式
def single(cls):
__isinstance = {}
def wrapper(*args,**kwargs):
if cls in __isinstance:
return __isinstance[cls]
else:
__isinstance[cls] = cls(*args,**kwargs)
return __isinstance[cls]
return wrapper
@single
class CustomClass:
pass
cc1 = CustomClass()
cc2 = CustomClass()
print(cc1 is cc2)
python之单例模式
最新推荐文章于 2023-07-26 15:46:48 发布