Python design pattern

Source: Internet
Author: User

A. Simple Factory mode

First look at the schematic diagram of the factory model:

Pattern Features: The factory produces classes of different functions according to conditions.

Program Example: Arithmetic calculator, according to the user's input produces the corresponding operation class, uses this operation class to handle the concrete operation.

Code Features: Switch...case ... The branch uses a dictionary instead.

Use the exception mechanism to process a divisor of 0.

The Python implementation code is as follows:

#!/usr/bin/env python#-*-coding:utf-8-*-# author:jason wangclass operation:def getresult (self): Passclass Operationadd (operation): Def getresult (self): return SELF.OP1 + self.op2class operationsub (operation): Def Ge TResult (self): return Self.op1-self.op2class Operationmul (operation): Def getresult (self): return to self.            OP1 * Self.op2class Operationdiv (operation): Def getresult (self): Try:result = Self.op1/self.op2            return result Except:print ("error:divided by Zero.")        return 0class Operationundef (operation): Def getresult (self): print ("undefine operation.")    return 0class operationfactory:operation = {} operation["+"] = Operationadd ();    operation["-"] = Operationsub ();    operation["*"] = Operationmul ();    operation["/"] = Operationdiv ();       def createoperation (self,ch): if ch in self.operation:op = self.operation[ch] Else:     op = operationundef () return opif __name__ = = "__main__": op = Input ("operator:") OPA = input ("A:") OPB = input ("B:") factory = Operationfactory () cal = Factory.createoperation (OP) cal.op1 = Int (OPA) cal.op2 = Int (OPB) print (Cal. GetResult ())
Simple Engineering Modetwo. Single-case mode

Schematic diagram:

Pattern Feature: guarantees that the class has only one instance and provides a global access point to access it.

Note: In order to achieve a single model cost a lot of work, and later found a blog post on this has a very detailed introduction, and the way of implementation is also very rich, through the code to learn more about the use of Python.

What I'm asking is, does Python really need a singleton mode? I'm referring to the singleton pattern in other programming languages.

The answer is: no need!

Because Python has a module, the most pythonic example of a single case.

module in one application only one, it is a singleton, the properties and methods you need, directly exposed in the module into the module's global variables and methods can!

#!/usr/bin/env python#-*-coding:utf-8-*-# author:jason wang#-*-encoding=utf-8-*-print ('---------------------- Method 1--------------------------') #方法1, implement the __new__ method # and bind an instance of a class to the class variable _instance, #如果cls. _instance to none indicates that the class has not yet been instantiated. Instantiate the class and return # if Cls._instance is not none, return directly to Cls._instanceclass Singleton (object): Def __new__ (CLS, *args, **kw): If not Hasattr (CLS, ' _instance '): Orig = Super (Singleton, cls) cls._instance = orig.__new__ (CLS, *args, **k W) return Cls._instanceclass MyClass (Singleton): a = 1one = MyClass () b = MyClass () two.a = 3print (one.a) #3 #one and Both are identical, can be detected by ID (), = =, is detection print (ID (one)) #29097904print (ID (one)) #29097904print (one = =) #Trueprint (one is) # Trueprint ('----------------------Method 2--------------------------') #方法2, shared properties; the so-called Singleton is all references (instances, objects) have the same state (attributes) and Behavior (method) # All instances of the same class naturally have the same behavior (methods), #只需要保证同一个类的所有实例具有相同的状态 (attributes) # The simplest and most straightforward way to share properties for all instances is to __dict__ the same dictionary (dict) #可参看: http:/ /code.activestate.com/recipes/66531/class Borg (object): _state = {} def __New__ (CLS, *args, **kw): OB = Super (Borg, CLS). __new__ (CLS, *args, **kw) ob.__dict__ = cls._state ret Urn Obclass MyClass2 (Borg): a = 1one = MyClass2 () b = MyClass2 () #one和two是两个不同的对象, id, = =, is comparison results can be seen two.a = 3print (one.a ) #3print (ID (one)) #28873680print (ID (one)) #28873712print (one = =) #Falseprint #False # but the same __dict__ properties), see: Print (ID (one.__dict__)) #30104000print (ID (two.__dict__)) #30104000print ('---------------------- Method 3--------------------------') # #通过类的静态字段构造类class CP: __instance = None def __init__ (self): Self.ip = "1.1.1. 1 "Self.port = 3306 self.pwd =" 123123 "self.user =" xxx "self.conn_list = [1,2,3,4,5,6] @s Taticmethod def get_instance (): If Cp.__instance:return cp.__instance else: # Create a Object and assigns the object to the static field __instance cp.__instance = CP () #执行init方且创建对象 and assigns a value to the private static field return Cp.__instance #将赋值的返回给 private static Field obj1 = Cp.get_instance () # Static field class calls print (OBJ1) Print ('----------------------method 4--------------------------') #方法4: Also the upgrade (advanced) version of Method 1, #使用装饰器 (decorator), # This is a more pythonic, more elegant approach, #单例类本身根本不知道自己是单例的, because he (his own code) is not a single-instance Def Singleton (CLS, *args, **kw): instances = {} def _s Ingleton (): If CLS not in instances:instances[cls] = CLS (*args, **KW) return INSTANCES[CLS] R Eturn _singleton@singletonclass MyClass4 (object): A = 1 def __init__ (self, x=0): self.x = Xone = MYCLASS4 () tw o = MyClass4 () two.a = 3print (ONE.A) #3print (ID (one)) #29660784print (ID (a)) #29660784print (one = =) #Trueprint (one = #Trueone. x = 1print (one.x) #1print (two.x) #1
single-case modeThree. Policy mode

Schematic diagram:

Pattern Features: Define the algorithm family and encapsulate them separately, and they can be replaced with each other without affecting the client.

Program Example: Store cashier software, need to be based on different sales strategy way to charge

Code features: Unlike in the same example 1, the dictionary is used here to avoid pitfalls where the keyword does not cause bugs in the dictionary.

#!/usr/bin/env python#-*-coding:utf-8-*-# author:jason wangclass cashsuper:def acceptcash (Self,money): RET Urn 0class cashnormal (cashsuper): def acceptcash (Self,money): Return moneyclass cashrebate (cashsuper): Discou NT = 0 def __init__ (self,ds): Self.discount = ds def acceptcash (Self,money): Return money * Self.disco    Untclass Cashreturn (cashsuper): total = 0;    ret = 0; def __init__ (self,t,r): self.total = t Self.ret = R def acceptcash (Self,money): if (money>=self . Total): Return Money-self.ret else:return moneyclass cashcontext:def __init__ (self,cs Uper): Self.cs = Csuper def getresult (Self,money): Return Self.cs.AcceptCash (Money) if __name__ = = "__main __ ": Money = Input (" Money: ") strategy = {} strategy[' 1 '] = Cashcontext (Cashnormal ()) strategy[' 2 '] = Cashconte XT (Cashrebate (0.8)) strategy[' 3 '] = Cashcontext (Cashreturn (300,100)) CType = inPut ("Type:[1]for normal,[2]for 80% discount [3]for 300-100.") Print () print (Strategy.keys ()) If CType in Strategy.keys (): CC = Strategy[ctype] Else:print ("Undef INE type.        Use normal mode. ") CC = strategy[1] Print ("You'll pay:%d"% (CC. GetResult (int (money))))
Policy Mode

Four. Decoration mode

Schematic diagram:

Pattern Features: Add additional responsibilities dynamically to objects

Program Example: show a person to dress the process of one piece.

Code Features: None

#!/usr/bin/env python#-*-coding:utf-8-*-#  author:jason wangclass Person:    def __init__ (self,tname):        Self.name = Tname    def Show (self):       print ("Dressed%s"% (Self.name)) class finery (person):    componet = None    def __init__ (self):        pass    def decorate (self,ct):        self.componet = CT    def Show (self):        if ( Self.componet!=none):            self.componet.Show () class Tshirts (finery):    def __init__ (self):        pass    def Show (self):        print ("Big T-shirt")        self.componet.Show () class Bigtrouser (finery):    def __init__ ( Self):        pass    def Show (self):        print ("Big trouser")        self.componet.Show () if __name__ = = "__main__":    p = person ("Somebody")    BT = Bigtrouser ()    ts = tshirts ()    BT. Decorate (p)    TS. Decorate (BT)    ts. Show ()
Decoration ModeIv. Proxy Mode

Schematic diagram:

Pattern Features: Provides a proxy for other objects to control access to this object.

Example of a program: The characteristic description of the same pattern.

Code Features: None

Class Interface:    def request:    return 0class realsubject (Interface):     def request (self):        print " Real request. " Class Proxy (Interface):    def Request (self):        self.real = Realsubject ()        self.real.Request () if __name__ = = "_ _main__ ":    p = Proxy ()    p.request ()
ProxyFive, factory method mode

Schematic diagram:

Pattern feature: Defines an interface for creating objects, letting subclasses decide which class to instantiate. This causes the instantiation of a class to be deferred to its subclasses.

Program examples: The base class Lei Feng class, derived from the student class and volunteer class, by the two seed classes to complete the "learn Lei Feng" work. The creation of subclasses is done by the corresponding subclasses of the Lei Feng factory.

Code Features: None

#!/usr/bin/env python#-*-coding:utf-8-*-#  author:jason wangclass leifeng:    def Sweep (self):        print (" Leifeng sweep ") class Student (Leifeng):    def sweep (self):        print (" Student sweep ") class Volenter (Leifeng):    def Sweep (self):        print ("Volenter Sweep") class Leifengfactory:    def Createleifeng (self):        temp = Leifeng ()        return Tempclass studentfactory (leifengfactory):    def Createleifeng (self):        temp = Student ()        Return Tempclass volenterfactory (leifengfactory):    def Createleifeng (self):        temp = volenter ()        return Tempif __name__ = = "__main__":    SF = studentfactory ()    s=sf. Createleifeng ()    s.sweep ()    SDF = volenterfactory ()    sd=sdf. Createleifeng ()    SD. Sweep ()
FactoryVI. Prototype Model

Pattern Features: Use prototype instances to specify the kind of objects that are created, and create new objects by copying those prototypes.

Example of a program: Create a new resume from a CV prototype

Code features: Resume class Resume provides a clone () method that is not actually clone, but adds a reference to an existing object.

The copy and Deepcopy methods in the Copy module provided by Python have implemented prototype patterns, but because of the shallow level of the examples, they do not see the difference.

#!/usr/bin/env python#-*-coding:utf-8-*-# author:jason wangimport copyclass workexp:place= "" Year=0class Resum  E:name = ' age = 0 def __init__ (self,n): Self.name = n def setage (self,a): Self.age = a def Setworkexp (self,p,y): Self.place = P self.year = y def Display (self): print (self.age) prin T (self.place) print (self.year) def clone (self): #实际不是 "clone", but returns itself return selfif __name__ = = "__main__" : a = Resume ("a") B = A.clone () c = Copy.copy (a) d = copy.deepcopy (a) a.setage (7) b.setage (a) C.seta GE (d.setage) a.setworkexp ("Primaryschool", 1996) B.setworkexp ("Midschool", 2001) C.setworkexp ("HighSchool ", 2004) D.setworkexp (" University, ") A.display () B.display () C.display () D.display () print (' A ID is% S '%id (a)) print (' B ID is%s '%id (b)) print (' C-ID is%s '%id (c)) print (' D-ID is%s '%id (d)) # # #运行结果 "" "12midschool2 00112midschool200115highSCHOOL200418UNIVERSITY2007A ID is 4323180160b ID is 4323180160c ID are 4323180216d ID is 4323180384 "" " 
prototype Mode

Seven, template method mode

Schematic diagram:

Python design pattern

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.