标签:style blog http color io ar 2014 div 代码
简单工厂模式又称之为静态工厂方法,属于创建型模式。在简单工厂模式中,可以根据传递的参数不同,返回不同类的实例。简单工厂模式定义了一个类,这个类专门用于创建其他类的实例,这些被创建的类都有一个共同的父类。
说明:加减乘除运算,继承同一个运算类。运算工厂根据传入参数返回相应的运算类。
代码:
1 class Operation(object): 2 def __init__(self, op1,op2): 3 self.op1 = op1 4 self.op2 = op2 5 6 def GetResult(): 7 pass 8 9 class Add(Operation): 10 def GetResult(self): 11 return self.op1+self.op2 12 class Sub(Operation): 13 def GetResult(self): 14 return self.op1-self.op2 15 class Mul(Operation): 16 def GetResult(self): 17 return self.op1*self.op2 18 class Div(Operation): 19 def GetResult(self): 20 try: 21 return self.op1/self.op2 22 except: 23 print ‘divided by zero!‘ 24 return 0 25 class undef(Operation): 26 def GetResult(self): 27 print ‘undefine operation‘ 28 return 0 29 30 class OperationFactory(object): 31 def CreateOperation(self,operation,op1,op2): 32 self.operations = { 33 ‘+‘:Add(op1,op2), 34 ‘-‘:Sub(op1,op2), 35 ‘*‘:Mul(op1,op2), 36 ‘/‘:Div(op1,op2) 37 } 38 if operation in self.operations.keys(): 39 return self.operations[operation] 40 else: 41 return undef(op1,op2) 42 43 if __name__==‘__main__‘: 44 factory = OperationFactory() 45 operation = factory.CreateOperation(‘+‘,1,2) 46 print operation.GetResult() 47 48 operation = factory.CreateOperation(‘-‘,1,2) 49 print operation.GetResult() 50 51 operation = factory.CreateOperation(‘*‘,1,2) 52 print operation.GetResult() 53 54 operation = factory.CreateOperation(‘/‘,1,2) 55 print operation.GetResult() 56 57 operation = factory.CreateOperation(‘#‘,1,2) 58 print operation.GetResult()
运行结果:
参考来源:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html
标签:style blog http color io ar 2014 div 代码
原文地址:http://www.cnblogs.com/wang-shuai/p/3930697.html