python单例装饰器

单例是设计结构中一种常见的模式。在工程中,确保一个实例、确保日志被初始化一次等,就可以使用单例。下面是使用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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
singleton decorator

usage:

decorete function: this function just be executed once.
@singlenton
def fun():
# do something
return

decorate class: this class just have one instance.
@singleton
class MyClass(object):
def __init__():
pass
"""

def singleton(cls):
instances = {}
def _singleton(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton