1. Single-case mode
An out-of-class adorner implements a singleton pattern, which intercepts the entire instantiation process. (__new__;__init__)
defSingleton (CLS): _instance= {} defFunc (*args,**Kwargs):ifCls not inch_instance: _instance[cls]= CLS (*args,**Kwargs)return_instance[cls]returnFunc@singletonclassTest (object):def __init__(self,name): Self.name=nameif __name__=='__main__': A= Test ('BOB') b= Test ('JON') Print(A isb)Print(ID (a), id (b))
Above, we define an adorner singleton, which returns an internal function, Func,
The function will determine if a class is in the dictionary _instances, and if it does not exist, the CLS will be stored as value key,cls (*args, **kwargs) in _instances.
Otherwise, return directly to _instances[cls].
classSingleton (object): _instance=Nonedef __new__(CLS, *args, * *Kwargs):if notcls._instance:cls._instance= object.__new__(cls,*args,**Kwargs)returncls._instanceclassTest (Singleton):def __init__(self): Self.name='Bob'if __name__=='__main__': A=Test () b=Test ()Print(A isb
*************************************************************************************************************** **********************************
# instance_dict = {}
#
# class B (object):
# __float = 0
#
# def __new__ (CLS, *args, **kwargs):
# If CLS not in Instance_dict:
# Instance_dict[cls] = object.__new__ (CLS, *args, **kwargs)
#
# return INSTANCE_DICT[CLS]
#
# def __init__ (self, name):
# If self.__float = = 0:
# Self.my_name = name
# Self.__float = 1
#
#
# if __name__ = = ' __main__ ':
# A = B (1)
# B = B (2)
# Print A.my_name, b.my_name
The implementation of singleton patterns within a class, only intercepts the process of __new__ generation objects, and does not intercept the initialization of instance properties
The interception __new__ method realizes the single case mode, the new type mainly
python-Single-case mode & Factory mode