Python如何实现单例模式?其他23种设计模式python如何实现?

 1 #使用装饰器(decorator),  
 2 #这是一种更pythonic,更elegant的方法,  
 3 #单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的  
 4 def singleton(cls, *args, **kw):  
 5     instances = {}  
 6     def _singleton():  
 7         if cls not in instances:  
 8             instances[cls] = cls(*args, **kw)  
 9         return instances[cls]  
10     return _singleton  
11  
12 @singleton  
13 class MyClass4(object):  
14     a = 1  
15     def __init__(self, x=0):  
16         self.x = x  
17  
18 one = MyClass4()  
19 two = MyClass4()  
20  
21 two.a = 3  
22 print one.a  
23 #3  
24 print id(one)  
25 #29660784  
26 print id(two)  
27 #29660784  
28 print one == two  
29 #True  
30 print one is two  
31 #True  
32 one.x = 1  
33 print one.x  
34 #1  
35 print two.x  
36 #1  
posted @ 2020-12-31 17:15  QC_der  阅读(59)  评论(0编辑  收藏  举报
返回顶端