基本介绍
一个对象只允许被一次创建,一个类只能创建一个对象,并且提供一个全局访问点。
单例模式应该是应用最广泛,实现最简单的一种创建型模式。
特点:全局唯一,允许更改
优缺点
优点:
- 避免对资源的多重占用,如写入文件操作
- 节省内存
- 防止命名空间被污染
缺点:
- 没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化
Python实现
方式1,元类实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class MetaClass( type ): def __call__( self , * args, * * kwargs): """ self : class Singleton """ if not hasattr ( self , "ins" ): insObject = super (__class__, self ).__call__( * args, * * kwargs) setattr ( self , "ins" , insObject) return getattr ( self , "ins" ) class Singleton( object , metaclass = MetaClass): pass if __name__ = = "__main__" : ins = Singleton() print ( id (ins)) ins = Singleton() print ( id (ins)) |
方式2,继承实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class ParentClass: def __new__( cls , * args, * * kwargs) - > object : """ cls : class Singeton """ if not hasattr ( cls , "ins" ): insObject = super (__class__, cls ).__new__( cls , * args, * * kwargs) setattr ( cls , "ins" , insObject) return getattr ( cls , "ins" ) class Singleton(ParentClass): pass if __name__ = = "__main__" : ins = Singleton() print ( id (ins)) ins = Singleton() print ( id (ins)) |
方式3,装饰器实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
def warpper(clsObject): def inner( * args, * * kwargs): if not hasattr (clsObject, "ins" ): insObject = clsObject( * args, * * kwargs) setattr (clsObject, "ins" , insObject) return getattr (clsObject, "ins" ) return inner @warpper class Singleton: pass if __name__ = = "__main__" : ins = Singleton() print ( id (ins)) ins = Singleton() print ( id (ins)) |
方式4,模块实现:
1
2
|
- foo.py - - > ins = Singleton() - bar.py - - > from foo import ins |
方式5,@classmethod实现单例模式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Singleton: @classmethod def getSingletonInstanceObject( cls , * args, * * kwargs): if not hasattr ( cls , "ins" ): insObject = cls ( * args, * * kwargs) setattr ( cls , "ins" , insObject) return getattr ( cls , "ins" ) if __name__ = = "__main__" : ins = Singleton.getSingletonInstanceObject() print ( id (ins)) ins = Singleton.getSingletonInstanceObject() print ( id (ins)) |
到此这篇关于Python实现单例模式的5种方法的文章就介绍到这了,更多相关Python 单例模式内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/Yunya-Cnblogs/p/14880267.html