- 单例模式:
法一:通过类的new()方法,但是个人感觉没有装饰器方便
1 | class Singleton(object): |
- 用装饰器来实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17def singleton(cls, *args, **kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
class MyClass1(object):
aa = 56
instance1 = MyClass1()
instance2 = MyClass1()
print id(instance1)
#139764123790288
print id(instance2)
#139764123790288