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
import logging
from functools import wraps

# wrapper

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')

logger = logging.getLogger('tts')


def log_func(level):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if level == 'warning':
logger.warning('enter func:{}'.format(func.__name__))
else:
logger.info('enter func:{}'.format(func.__name__))
return func(*args, **kwargs)
return wrapper
return decorator


@log_func(level="warning")
def foo(name='foo', k='88'):
print 'i am foo:{} k:{}'.format(name, k)
foo(name='oo', k=2)

单例模式实现

1. cls单例模式实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# singleton
#
from functools import wraps
def singleton(cls):
_instance = {}

@wraps(cls)
def inner(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return innerr


@singleton
class Cls(object):
def __init__(self):
pass

cls1 = Cls()
cls2 = Cls()

print(id(cls1) == id(cls2))

2. call实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 2. __call__
class Singleton(object):
def __init__(self, cls):
self._cls = cls
self._instance = {}

def __call__(self):
if self._cls not in self._instance:
self._instance[self._cls] = self._cls()
return self._instance[self._cls]
@Singleton
class Cls2(object):
def __init__(self):
pass
cls1 = Cls()
cls2 = Cls()
print(id(cls1) == id(cls2))

3. new实现单例

1
2
3
4
5
6
7
8
9
10
11
12
13
class SingletonNew(object):
_instance = {}

def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance

def __init__(self):
pass
single1 = SingletonNew()
single2 = SingletonNew()
print id(single1) == id(single2)

4. metaclass单例实现

1
2
3
4
5
6
7
8
9
10
11
12
13
class Single(type):
_instance = {}

def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super(Single, cls).__call__(*args, **kwargs)
return cls._instance[cls]
class Cls(object):
__metaclass__ = Single
pass

cls1, cls2 = Cls(), Cls()
print id(cls1) == id(cls2)
  • 个人比较推荐第一种和第二种实现方式:代码量较少,并且简单易懂