装饰器模式实现单例
from functools import wraps
def singleton(cls):
instances = {}
@wraps(cls)
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Second:
def __init__(self, config):
self.config = config
def print_config(self):
print(self.config)
通过拦截类创建的是模式实现单例
class SingletonCls(type):
instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls.instance:
cls.instance[cls] = super().__call__(*args, **kwargs)
return cls.instance[cls]
class Base(metaclass=SingletonCls):
def __init__(self, config):
self.config = config
def print_config(self):
print(self.config)
测试结果
if __name__ == '__main__':
b = Base("145")
b.print_config()
c = Base("234")
c.print_config()
print("---装饰器实现---")
d = Second("k8s")
d.print_config()
e = Second("k3s")
e.print_config()