标签:
1.由于语言的特性不同,设计模式的实现方式和实现难度也会不同
2.有的模式已经在语言内置了,比如迭代器模式。
3.单例模式可以直接用模块级变量来实现
4.普通工厂模式可以直接通过传入“类名”作为参数实现
单例模式实例:
12_eg.py
class SingleClass:
def __init__(self,x=0):
self.x = 0
sc = SingleClass()
def tsc():
print(sc.x)
sc.x = 10
print(sc.x)
def tsc2():
print(sc.x)
sc.x = 9
print(sc.x)
if __name__ == ‘__main__‘:
tsc()
tsc2()
程序的运行结果为:
12_egs.py
class Singleton:
def __new__(cls,*args,**kwargs):
if not hasattr(cls,‘_sgl‘):
cls._sgl = super().__new__(cls,*args,**kwargs)
return cls._sgl
if __name__ == ‘__main__‘:
sa = Singleton()
sb = Singleton()
print(id(sa))
print(id(sb))
程序的运行结果为:
通过传入“类名”作为参数实现:
12_eg2.py
class Ab:
a = 3
class Ac:
a = 0
class MyFactory:
def get_instance(self,ins):
return ins()
if __name__ == ‘__main__‘:
mf = MyFactory()
print(type(mf.get_instance(Ab)))
print(type(mf.get_instance(Ac)))
程序的运行结果为:
原文链接:http://www.maiziedu.com/wiki/python/designpattern/
标签:
原文地址:http://www.cnblogs.com/space007/p/5953829.html