python 练手 单例模式
python 2.7
写一个单例模式练手,使用__new__初始化唯一实例,并判断返回,给实例__双下滑线内部变量防止外部直接读取修改该变量,反正是练手,又增加类似工厂模式,根据传入的type值不同,返回不同的单例。
其他涉及__call__方法重写 实例(),__add__方法重写+运算符,使用__getitem__和__setitem__来设置读取属性。
class Singleton(object):
'''单例模式类'''
__type = {
'menu': '',
'dept': '',
'status': ''
}
def __new__(cls, *args, **kwargs):
'''构造'''
if len(kwargs)!=0 and 'type' in kwargs and kwargs['type'] in Singleton.__type:
if not isinstance(Singleton.__type[kwargs['type']],Singleton):
Singleton.__type[kwargs['type']]=super(Singleton,cls).__new__(cls)
else:
raise Exception ('请传入正确的值type,且已写入__type中');
# return Singleton._inst
return Singleton.__type[kwargs['type']]
def __init__(self,type):
'''初始化'''
if not hasattr(self,'_Singleton__dict'):
self.__dict={}
# def __del__(self):
# '''销毁'''
# pass
def __setitem__(self, key, value):
'''赋值'''
self.__dict[key]=value
def __getitem__(self, item=None):
'''获取值'''
if item==None:
return self.__dict
else:
try:
_v= self.__dict[item]
except Exception ,err:
_v=None
finally:
return _v
def __call__(self, *args, **kwargs):
return self.__dict
def __add__(self, other):
_d=self.__dict.copy();
for i in other():
if i not in self.__dict:
_d[i]=other[i]
return _d;
a=Singleton(type='menu') #type为menu的单例
print a() #{}
a[1]=1 #赋值
print a[6] #None
print a() #{1:1}
b=Singleton(type='menu') #仍为单例
b['b']=2 #赋值
print b() #{1: 1, 'b': 2}
print b[1] #1
print b['b'] #2
c=Singleton(type='dept') #另一个type为dept的单例
c['r']=0 #赋值
print c['r'] #0
print c() #{'r':0}
print c+b #{1:1,'r':0,'b':2}
print c() #{'r':0}
# print c.__dict #直接获取或意图改动内容值会报错