python单例模式

1、使用__new__方法

class Single(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        pass
__new__

2、函数装饰器

def single(cls):
    _instance = {}

    def inner(*args, **kw):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kw)
        return _instance[cls]
    return inner

@single
class Cls(object):
    pass
函数装饰器

3、import

python的模块是天然的单例模式

# singleton.py
class Single(object):
    def __init__(self, name):
        self.name = name
single = Single('Alice')

# use
from singleton import single
print(single.name)
import

 

posted @ 2019-05-05 16:35  houyongchong  阅读(117)  评论(0编辑  收藏  举报