标签:
简单工厂模式(Factory Pattern)是一种创建型的设计模式,像工厂一样根据要求生产对象实例。
特点:根据不同的条件,工厂实例化出合适的对象。
《大话设计模式》中实例:四则运算计算器
代码:
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 4 class Operation: 5 def getResult(self): 6 pass 7 8 class OperationAdd(Operation): 9 def getResult(self): 10 return self.op1+self.op2 11 12 class OperationSub(Operation): 13 def getResult(self): 14 return self.op1-self.op2 15 16 class OperationMul(Operation): 17 def getResult(slef): 18 return self.op1*self.op2 19 20 class OperationDiv(Operation): 21 def getResult(self): 22 try: 23 return self.op1/float(self.op2) 24 except: 25 print("Error:除数为0!") 26 return 0 27 28 class OperationOther(Operation): 29 def getResult(self): 30 print("Error:没有定义的运算符!") 31 return 0 32 33 34 class OperationFactory: 35 36 operation = {} 37 operation["+"] = OperationAdd() 38 operation["-"] = OperationSub() 39 operation["*"] = OperationMul() 40 operation["/"] = OperationDiv() 41 42 def createOperation(self,choice): 43 if choice in self.operation.keys(): 44 op = self.operation[choice] 45 else: 46 op = OperationOther() 47 return op 48 49 50 51 if __name__ == "__main__": 52 op = raw_input("请输入运算符:") 53 num_a = input("a:") 54 num_b = input("b:") 55 56 factory = OperationFactory() 57 cal = factory.createOperation(op) 58 59 cal.op1 = num_a 60 cal.op2 = num_b 61 62 print(u"运算结果为:" + str(cal.getResult())) 63
当需要使用到单个实体的多个变体时,可以使用工厂模式。例如上面的例子中,需要做运算(单个实体),然而常用的运算包括加、减、乘、除(变体),不同的条件下需要创建不同的变体,这时就可以通过工厂来创建不同的运算。
步骤:
class Entity(): #实体 def Func(self): "方法体"
#pass
class Variant1(Entity): def Func(self):
pass class Variant2(Entity): def Func(self):
pass
class EntityFactory(): def create_variant(self,choice): #根据choice创建不同的variant类 #函数体 #return
使用工厂类:
factory = EntityFactory() variant = factory.create_variant(choice) print(variant.Func())
标签:
原文地址:http://www.cnblogs.com/cloudPython/p/4912583.html