美文网首页
python单例模式的几种写法

python单例模式的几种写法

作者: guoweikuang | 来源:发表于2018-02-02 17:29 被阅读180次

    一、装饰器模式

    def singleton(cls, *args, **kwargs):
        instance = {}
        def _singleton():
            if cls not in instance:
                instance[cls] = cls(*args, **kwargs)
            return instance[cls]
        return _sigleton
    
    @singleton
    class Test(object):
        a = 1
        
    test = Test()
    test1 = Test()
    print(id(test) == id(test1))
                
    >>> True
    

    二、使用new方法

    class Singleton(object):
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls, '_instance'):
                cls._instance = super(Singleton, cls).__new__(cls, *args, **kargs)
            return cls._instance
            
    class Test(Singleton):
        a = 1
        
    test = Test()
    test1 = Test()
    print(id(test) == id(test1))
    >>> True
    

    三、共享dict方法

    class Singleton(object):
        _state = {}
        def __new__(cls, *args, **kwargs):
            obj = super(Singleton, cls).__new__(cls, *args, **kwargs)
            obj.__dict__ = obj._state
            return obj
            
    class Test(Singleton):
        a = 1
        
    test = Test()
    test1 = Test()
    print(id(test) == id(test1))
    print(id(test.__dict__) == id(test1.__dict__))
    >>> False
    >>> True
    

    四、import导入

    # a.py
    class Test(object):
        a = 1
    test = Test()
    
    # b.py
    from a import test
    print(id(test))
    
    # c.py
    from a import test
    print(id(test))
    
    

    相关文章

      网友评论

          本文标题:python单例模式的几种写法

          本文链接:https://www.haomeiwen.com/subject/sxvezxtx.html