python-单例模式&工厂模式
1.单例模式
类外装饰器实现单例模式,是拦截整个实例化过程。(__new__;__init__)
def singleton(cls): _instance = {} def func(*args,**kwargs): if cls not in _instance: _instance[cls] = cls(*args,**kwargs) return _instance[cls] return func @singleton class Test(object): def __init__(self,name): self.name = name if __name__ == '__main__': a = Test('BOB') b = Test('JON') print(a is b) print(id(a),id(b))
在上面,我们定义了一个装饰器 singleton,它返回了一个内部函数 func,
该函数会判断某个类是否在字典 _instances 中,如果不存在,则会将 cls 作为 key,cls(*args, **kwargs) 作为 value 存到 _instances 中,
否则,直接返回 _instances[cls]。
class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = object.__new__(cls,*args,**kwargs) return cls._instance class Test(Singleton): def __init__(self): self.name = 'bob' if __name__ == '__main__': a = Test() b = Test() print(a is b)
*************************************************************************************************************************************************
# instance_dict = {}
#
# class B(object):
# __float = 0
#
# def __new__(cls, *args, **kwargs):
# if cls not in instance_dict:
# instance_dict[cls] = object.__new__(cls, *args, **kwargs)
#
# return instance_dict[cls]
#
# def __init__(self, name):
# if self.__float == 0:
# self.my_name = name
# self.__float = 1
#
#
# if __name__ == '__main__':
# a = B(1)
# b = B(2)
# print a.my_name, b.my_name
类内实现单例模式,只拦截了__new__生成对象的过程,没有拦截初始化实例属性的过程
拦截__new__方法实现单例模式,新式类为主