简介:单例模式可以保证一个类仅有一个实例,并提供一个访问它的全局访问点。适用性于当类只能有一个实例而且客户可以从一个众所周知的访问点访问它,例如访问数据库、MQ等。
实现方式:
1、通过导入模块实现
2、通过装饰器实现
3、通过使用类实现
4、通过__new__ 方法实现
单例模块方式被导入的源码:singleton.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# -*- coding: utf-8 -*- # time: 2022/5/17 10:31 # file: singleton.py # author: tom # 公众号: 玩转测试开发 class Singleton( object ): def __init__( self , name): self .name = name def run( self ): print ( self .name) s = Singleton( "Tom" ) |
主函数源码:
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
# -*- coding: utf-8 -*- # time: 2022/5/17 10:51 # file: test_singleton.py # author: tom # 公众号: 玩转测试开发 from singleton import s as s1 from singleton import s as s2 # Method One:通过导入模块实现 def show_method_one(): """ :return: """ print (s1) print (s2) print ( id (s1)) print ( id (s2)) show_method_one() # Method Two:通过装饰器实现 def singleton( cls ): # 创建一个字典用来保存类的实例对象 _instance = {} def _singleton( * args, * * kwargs): # 先判断这个类有没有对象 if cls not in _instance: _instance[ cls ] = cls ( * args, * * kwargs) # 创建一个对象,并保存到字典当中 # 将实例对象返回 return _instance[ cls ] return _singleton @singleton class Demo2( object ): a = 1 def __init__( self , x = 0 ): self .x = x a1 = Demo2( 1 ) a2 = Demo2( 2 ) print ( id (a1)) print ( id (a2)) # Method Three:通过使用类实现 class Demo3( object ): # 静态变量 _instance = None _flag = False def __new__( cls , * args, * * kwargs): if cls ._instance is None : cls ._instance = super ().__new__( cls ) return cls ._instance def __init__( self ): if not Demo3._flag: Demo3._flag = True b1 = Demo3() b2 = Demo3() print ( id (b1)) print ( id (b2)) # Method Four:通过__new__ 方法实现 class Demo4: def __new__( cls , * args, * * kwargs): if not hasattr ( cls , '_instance' ): cls ._instance = super (Demo4, cls ).__new__( cls ) return cls ._instance c1 = Demo4() c2 = Demo4() print ( id (c1)) print ( id (c2)) |
运行结果:
到此这篇关于Python实现单例模式的四种方式详解的文章就介绍到这了,更多相关Python单例模式内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/hzblucky1314/article/details/124833122