单例模式
Posted huikejie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
# 单例模式 # 模式一基于@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 #基于模块的导入单例
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章