单例模式

# 单例模式

# 模式一基于@classmethod
class test:
    _instance = None

    def __init__(self, name=None):
        self.name = name

    @classmethod
    def singlenton(cls):
        if not cls._instance:
            cls._instance = test(name='hkj')
        return cls._instance


obj1 = test().singlenton()
obj2 = test().singlenton()


# 单例模式二基于装饰器
def outer(cls):
    _instance = cls('hkj')
    def inner(*args, **kwargs):
        if args or kwargs:
            obj = cls(*args, **kwargs)
            return obj
        else:
            return _instance
    return inner


@outer
class test2:
    def __init__(self, name):
        self.name = name


obj3 = test2()
obj4 = test2()


#基于__call__ 基于元类
class MyMeta(type):
    def __new__(cls,name,bases,dic):
        print(name,bases,dic)
        return super().__new__(cls,name,bases,dic)

    def __call__(self, *args, **kwargs):

        if not getattr(self, '_instance'):
            self._instance = super().__call__(*args, **kwargs)
        return self._instance


class test3(metaclass=MyMeta):
    _instance = None
    def __init__(self, name):
        print(222)
        self.name = name



#基于模块的导入单例

 

posted @ 2019-07-31 17:19  huikejie  阅读(110)  评论(0编辑  收藏  举报