Simple Factory Pattern: You are responsible for creating instances of other classes by defining a class specifically, and the instances that are created typically have a common parent class.
A simple arithmetic is implemented using the Simple Factory mode
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 4 __author__='Andy'5 6 " "7 Liar design Mode8 Implement a calculator console program with any object-oriented language. Requires two numbers and arithmetic symbols to get results9 design mode-Simple Factory modeTen Simple Factory Pattern: You are responsible for creating instances of other classes by defining a class specifically, and the instances that are created typically have a common parent class. One " " A - classoperation (object): - " " the The parent class of the arithmetic that receives the value entered by the user - " " - def __init__(Self, number1=0, number2=0): -SELF.NUM1 =Number1 +Self.num2 =number2 - + defGetResult (self): A Pass at Pass - - #addition Operation class - classOperationadd (operation): - defGetResult (self): - returnSELF.NUM1 +self.num2 in - #Subtraction Operation class to classOperationsub (operation): + defGetResult (self): - returnSELF.NUM1-self.num2 the * #Multiply Operations Class $ classOperationmul (operation):Panax Notoginseng defGetResult (self): - returnSELF.NUM1 *self.num2 the + #Division Operation Class A classOperationdiv (operation): the defGetResult (self): + ifSelf.num2 = =0: - return 'the divisor cannot be 0' $ return1.0*SELF.NUM1/self.num2 $ - #Other operator Classes - classOperationundef (operation): the defGetResult (self): - return 'operator Error'Wuyi the #Simple Factory class - classOperationfactory (object): Wu defChoose_oper (self,ch): - ifch = ='+': About returnOperationadd () $ elifch = ='-': - returnoperationsub () - elifch = ='*': - returnOperationmul () A elifch = ='/': + returnOperationdiv () the Else: - returnoperationundef () $ the if __name__=="__main__": theCH ="' the while notch = ='Q': theNUM1 = input ('Please enter the first value:') -oper = str (raw_input ('Please enter a arithmetic character:')) innum2 = input ('Please enter a second value:') the #operation (NUM1,NUM2) theof =operationfactory () AboutOper_obj =Of.choose_oper (Oper) theOPER_OBJ.NUM1 =NUM1 theOper_obj.num2 =num2 the Print 'The result of the operation is:', Oper_obj. GetResult ()
The structure of these classes is shown below:
Specifically defines a operation class as the parent class, the subtraction class inherits the Operation class, and the Operationfactory class is used to determine when to create the corresponding class
Andy
Source: http://www.cnblogs.com/onepiece-andy/
The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the author's consent must be in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
Big talk involves pattern Python implementation-Simple Factory mode