1. due to the different characteristics of the language, the design mode and implementation of the difficulty will be different
2. Some patterns have been built into the language, such as the iterator pattern.
3. The singleton mode can be directly implemented with module-level variables .
4. Normal Factory mode can be implemented directly by passing in "class name" as parameter
Singleton Mode Example:
12_eg.py
Class Singleclass:
def __init__ (self,x=0):
self.x = 0
sc = Singleclass ()
Def TSC ():
Print (sc.x)
sc.x = 10
Print (sc.x)
Def TSC2 ():
Print (sc.x)
sc.x = 9
Print (sc.x)
if __name__ = = ' __main__ ':
TSC ()
TSC2 ()
The running result of the program is:
12_egs.py
Class Singleton:
def __new__ (Cls,*args,**kwargs):
If not hasattr (CLS, ' _SGL '):
CLS._SGL = Super (). __new__ (Cls,*args,**kwargs)
Return CLS._SGL
if __name__ = = ' __main__ ':
SA = Singleton ()
SB = Singleton ()
Print (ID (SA))
Print (ID (SB))
The running result of the program is:
Implemented by passing in the "class name" as a parameter:
12_eg2.py
Class Ab:
A = 3
Class Ac:
A = 0
Class MyFactory:
def get_instance (self,ins):
return ins ()
if __name__ = = ' __main__ ':
MF = myfactory ()
Print (Type (mf.get_instance (Ab)))
Print (Type (mf.get_instance (Ac)))
The running result of the program is:
original link:http://www.maiziedu.com/wiki/python/designpattern/
A single-instance pattern of Python design patterns