设计之单例模式
1、设计模式之单例模式
"""
方式一:__new__
class Singleton:
__instance = None
def __new__(cls, *args, **kwags):
if not cls.__instance:
cls.__instance = objecet.__new__(cls)
return cls.__instance
obj1 = Singleton()
obj2 = Singleton()
方式二:classmethod
class Singleton:
__instance = None
@classmethod
def singleton(cls):
if not cls.__instance:
cls.__instance = cls()
return cls.__instance
obj1 = Singleton.singleton()
obj2 = Singleton.singleton()
方式三:装饰器
def singleton(cls);
——instance = {}
def inner(*args, **kwargs):
if cls not in __instance:
obj = cls(*args, **kwargs)
__instance[cls] = obj
return __instance[cls]
return inner
@singleton
class Func:
pass
print(Func())
print(Func())
"""
2、单例模式的优点和缺点
"""
单例模式的优点:
1、由于单例模式要求在全局内只有一个实例,因而可以节省比较多的内存空间;
2、全局只有一个接入点,可以更好的进行数据同步控制,避免多重占用;
单例模式的缺点:
1、单例模式的扩展是比较困难的;
2、单例模式是并发协作软件模块中需要最先完成的,因而其不利于测试
"""
Only you can control your future
You're not alone. You still have family,peopel who care for you and want to save you.