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 @   houyongchong  阅读(117)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示