这个模式,我还是了解的。
书上用了三种不同的方法。
class Singleton1: # 单例实现方式1 __instance = None __is_first_init = False def __new__(cls, name): if not cls.__instance: Singleton1.__instance = super().__new__(cls) return cls.__instance def __init__(self, name): if not self.__is_first_init: self.__name = name self.__is_first_init = True def get_name(self): return self.__name tony = Singleton1(‘Tony‘) karry = Singleton1(‘karry‘) print(tony.get_name(), karry.get_name()) print(id(tony), id(karry)) print(tony == karry) print("=======单例实现方式1========") class Singleton2(type): # 单例实现方式2 def __init__(cls, what, bases=None, dict=None): super().__init__(what, bases, dict) cls._instance = None def __call__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__call__(*args, **kwargs) return cls._instance class CustomClass(metaclass=Singleton2): def __init__(self, name): self.__name = name def get_name(self): return self.__name tony = CustomClass(‘Tony‘) karry = CustomClass(‘karry‘) print(tony.get_name(), karry.get_name()) print(id(tony), id(karry)) print(tony == karry) print("=======单例实现方式2========") def singleton_decorator(cls, *args, **kwargs): instance = {} def wrapper_singleton(*args, **kwargs): if cls not in instance: instance[cls] = cls(*args, **kwargs) return instance[cls] return wrapper_singleton @singleton_decorator class Singleton3: # 单例实现方式2 def __init__(self, name): self.__name = name def get_name(self): return self.__name tony = Singleton3(‘Tony‘) karry = Singleton3(‘karry‘) print(tony.get_name(), karry.get_name()) print(id(tony), id(karry)) print(tony == karry) print("=======单例实现方式3========")
C:\Python36\python.exe C:/Users/Sahara/PycharmProjects/test1/test.py Tony Tony 39257648 39257648 True =======单例实现方式1======== Tony Tony 39257984 39257984 True =======单例实现方式2======== Tony Tony 39257928 39257928 True =======单例实现方式3======== Process finished with exit code 0
原文地址:https://www.cnblogs.com/aguncn/p/11336409.html
时间: 2024-11-09 06:09:32