python-Single-case mode & Factory mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.