#Method 1: Define a class method to implement the singleton pattern import settings class Mysql: __instance=None def __init__(self,host,port): self.host=host self.port=port @classmethod def singleton(cls): if not cls.__instance: cls.__instance=cls(settings.HOST,settings.PORT) return cls.__instance obj1=Mysql('1.1.1.2',3306) obj2=Mysql('1.1.1.3',3307) print(obj1 is obj2) #False obj3=Mysql.singleton() obj4=Mysql.singleton() print(obj3 is obj4) #True #Method 2: Customize the metaclass to implement the singleton pattern import settings class Mymeta(type): def __init__(self,name,bases,dic): #Triggered when the class Mysql is defined # Take the configuration from the configuration file in advance to create an instance of Mysql self.__instance = object.__new__(self) # produce object self.__init__(self.__instance, settings.HOST, settings.PORT) # Initialize the object # The above two steps can be combined into the following step # self.__instance=super().__call__(*args,**kwargs) super().__init__(name,bases,dic) def __call__(self, *args, **kwargs): triggered when #Mysql(...) if args or kwargs: # There is a value in args or kwargs obj=object.__new__(self) self.__init__(obj,*args,**kwargs) return obj return self.__instance class Mysql(metaclass=Mymeta): def __init__(self,host,port): self.host=host self.port=port # # obj1=Mysql() # If no value is passed, the configuration is read from the configuration file to instantiate by default, all instances should point to a memory address obj2=Mysql() obj3=Mysql() print(obj1 is obj2 is obj3) obj4=Mysql('1.1.1.4',3307) print(obj1 is obj4) # Method 3: Define a decorator to implement the singleton pattern import settings def singleton(cls): #cls=Mysql _instance=cls(settings.HOST,settings.PORT) def wrapper(*args,**kwargs): if args or kwargs: obj=cls(*args,**kwargs) return obj return _instance return wrapper @singleton # Mysql=Singleton(Mysql) class Mysql: def __init__(self,host,port): self.host=host self.port=port obj1=Mysql() obj2=Mysql() obj3=Mysql() print(obj1 is obj2 is obj3) #True obj4=Mysql('1.1.1.3',3307) obj5=Mysql('1.1.1.4',3308) print(obj3 is obj4) #Fals
(python) three singleton patterns
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325752113&siteId=291194637
Recommended
Ranking