Python设计模式之单例模式
Python设计模式之单例模式
1.前提
在Python面向对象编程时,我们可能会遇到这样一类问题,那就是我们只需要创建一个某种类的实例,而不需要多余的实例被创建。比如:对数据库的修改实例,这样就可以做到对数据库的同步修改了,而不是造成数据库的混乱;或者是打印机的实例等,单例模式可以大大减小计算机的资源开销。
2.Python代码
2.1非单例模式
1 class Test():
2 def __init__(self,name):
3 self.name = name
4 print("this is test...",self.name)
5
6
7 t1 = Test("李四")
8 t2 = Test("张三")
9
10 print(t1==t2)
11 print("t1的地址:{0},t2的地址{1}".format(id(t1),id(t2)))
输出:
this is test... 李四
this is test... 张三
False
t1的地址:814304641880,t2的地址814304644512
2.2伪单例模式
1 class Test():
2 __instance = None
3 def __init__(self,name):
4 self.name = name
5 print("this is test...")
6
7 @classmethod
8 def getInstance(cls,name):
9 if not cls.__instance:
10 cls.__instance = Test(name)
11
12 return cls.__instance
13
14 t1 = Test.getInstance("李四")
15 t2 = Test.getInstance("张三")
16 print("t1和t2是同一个对象吗:",t1==t2)
17 print("t1的地址{0},t2的地址{1}".format(id(t1),id(t2)))
18 print("t1的名字:",t1.name,",t2的名字:",t2.name)
输出:
this is test...
t1和t2是同一个对象吗: True
t1的地址258018626976,t2的地址258018626976
t1的名字: 李四 ,t2的名字: 李四
解析:从代码中,我们可以看到,我们用代码创建了两个实例对象,但是输出结果里显示只有一个对象,t1和t2分别是这一个对象的不同的引用而已。它们的内存地址是相同的,所以是同一个对象。但是他们的name属性为什么是李四而不是张三呢,这是因为当程序在执行第14行代码时创建了一个对象,此时的内置属性__instance不在是None,而是新创建的对象,name属性也是第14行代码传入的值。当地15行代码再次调用该类创建对象时,发现内置属性__instance不在为None,所以就不执行第10行的代码,直接返回当先对象的实例,也即是第14行创建的实例。
2.3单例模式
1 class Test():
2 __instance = None
3 def __init__(self,name):
4 self.name = name
5 print("this is test...",self.name)
6
7 def __new__(cls, *args, **kwargs):
8 if not cls.__instance:
9 cls.__instance = object.__new__(cls)
10
11 return cls.__instance
12
13 t1 = Test("李四")
14 t2 = Test("张三")
15 print("t1和t2是同一个对象吗:",t1==t2)
16 print("t1的地址{0},t2的地址{1}".format(id(t1),id(t2)))
17 print("t1的名字:",t1.name,",t2的名字:",t2.name)
输出:
this is test... 李四
this is test... 张三
t1和t2是同一个对象吗: True
t1的地址677550539776,t2的地址677550539776
t1的名字: 张三 ,t2的名字: 张三
解析:我们从代码中可以看到,这里使用__new__魔法函数来实现单例模式,__new__和__init__的差别,我们这里暂不介绍,有时间我在写一个它们之间的差异的文章。在__new__方法中,我们还是使用了和上面类似的代码。最后的输出我们也看到了,它们就是同一个对象的不同引用,所以内存地址也是相同的。最后输出的名字和上面的刚好相反,这里是因为t1和t2都是Test()的引用,由于t2在t1之后对这个实例进行了修改,所以最后的name属性是后者的name属性值。此时虽然没有执行第9行的代码,但是这个实例还是被改变了,返回的是一个被修改过的实例。
posted @ 2019-04-04 21:58 东京的樱花在巴黎飘下 阅读(...) 评论(...) 编辑 收藏