直播电商平台开发,设计模式单例模式
1.说明
单例即只有一个实例,比如说配置、日志、连接池等,可以避免多个实例带来的多余的资源开销,并且在多线程环境下保证数据安全
2.类重写__new__
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls, *args, **args)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(id(s1), id(s2), s1 is s2)
3.装饰器
我们可以使用functools里的wraps装饰一下,它能保留原有函数的名称和函数属性
from functools import wraps
def singleton(cls):
instance = dict()
@wraps(cls)
def wrapper(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return wrapper
@singleton
class Person:
pass
s1 = Person()
s2 = Person()
print(id(s1), id(s2), s1 is s2)
4.元类
type创建类时自动调用__init__(),类在创建对象时会自动调用__call__()
class SingletonMeta(type):
def __init__(cls, *args, **kwargs):
cls._instance = None
super().__init__(*args, **kwargs)
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class Person(metaclass=SingletonMeta):
pass
s1 = Person()
s2 = Person()
print(id(s1), id(s2), s1 is s2)
5.加锁优化
如果不加锁,在多线程情况下可能会同时实例化对象
from threading import RLock
class Singleton:
_instance = None
_lock = RLock()
def __new__(cls, *args, **kwargs):
if cls._instance:
return cls._instance
with cls._lock:
if not cls._instance:
super().__new__(cls, *args, **kwargs)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(id(s1), id(s2), s1 is s2)
以上就是 直播电商平台开发,设计模式单例模式,更多内容欢迎关注之后的文章
标签:__,设计模式,s2,args,instance,单例,._,电商,cls From: https://www.cnblogs.com/yunbaomengnan/p/16821309.html