Python 实现单例模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
# 使用Python实现单例模式
# 方法一: 使用__new__方法
class
SingleTon(
object
):
def
__new__(
cls
,
*
args,
*
*
kwargs):
if
not
hasattr
(
cls
,
'_instance'
):
cls
._instance
=
object
.__new__(
cls
,
*
args,
*
*
kwargs)
return
cls
._instance
class
TestClass(SingleTon):
a
=
1
# 方法二: 使用装饰器(decorator)
def
SingleTon1(
cls
,
*
args,
*
*
kwargs):
instances
=
{}
def
_singleTon():
if
cls
not
in
instances:
instances[
cls
]
=
cls
(
*
args,
*
*
kwargs)
return
instances[
cls
]
return
_singleTon
@SingleTon1
class
TestClass1(
object
):
a
=
1
# 共享属性 属性是共享的,但是并非单例模式
class
SingleTon3(
object
):
_state
=
{}
def
__new__(
cls
,
*
args,
*
*
kwargs):
obj
=
object
.__new__(
cls
,
*
args,
*
*
kwargs)
obj.__dict__
=
cls
._state
return
obj
class
TestClass3(SingleTon3):
a
=
1
test1
=
TestClass3()
test2
=
TestClass3()
test1.a
=
2
print
(test1.a)
print
(test2.a)
print
(test1)
print
(test2)
|
本文转自 许大树 51CTO博客,原文链接:http://blog.51cto.com/abelxu/1967293,如需转载请自行联系原作者