Python之简单工厂模式实现

最近又看了下大话设计模式,决定用Python来试着实现下。

基础类

1 class OperationBase():
2     """
3     基础运算类
4     """
5     result = 0
6     def GetResult(self):
7         return self.result

继承类

 1 class OperationAdd(OperationBase):
 2     """
 3     加法类,继承基础运算类
 4     """
 5     def __init__(self,numA,numB):
 6         self.result = numA + numB
 7     def GetResult(self):
 8         return self.result
 9 
10 class OperationSub(OperationBase):
11     """
12     减法运算类,继承基础运算类
13     """
14     def __init__(self,numA,numB):
15         self.result = numA - numB
16     def GetResult(self):
17         return self.result
18 
19 class OperationMult(OperationBase):
20     """
21     乘法运算类,继承基础运算类
22     """
23     def __init__(self,numA,numB):
24         self.result = numA * numB
25     def GetResult(self):
26         return self.result
27 
28 class OperationDiv(OperationBase):
29     """
30     除法运算类,继承基础运算类,通过被除数为0异常捕获控制被除数不能为0
31     """
32     def __init__(self,numA,numB):
33         try:
34             self.result = numA / numB
35         except ZeroDivisionError:
36             print "除数不能为0!!!"
37 
38     def GetResult(self):
39         return self.result
40 
41 #工厂类
42 class OperationFactor():
43     @staticmethod
44     def createOperate(operate,numA,numB):
45         for case in switch(operate):
46             if case('+'):
47                 oper = OperationAdd(numA,numB)
48                 break
49             if case('-'):
50                 oper = OperationSub(numA,numB)
51                 break
52             if case('*'):
53                 oper = OperationMult(numA,numB)
54                 break
55             if case('/'):
56                 oper = OperationDiv(numA,numB)
57                 break
58         return oper
59 
60 if __name__ == '__main__':
61     opt = raw_input("请输入一个运算操作符(+-*/):")
62     try:
63         numA = float(raw_input("请输入第一个运算的数字:"))
64         numB = float(raw_input("请输入第二个运算的数字:"))
65     except ValueError:
66         print "输入数字不对,请重新输入!"
67         numA = float(raw_input("请输入第一个运算的数字:"))
68         numB = float(raw_input("请输入第二个运算的数字:"))
69 
70     oper = OperationFactor.createOperate(opt,float(numA),float(numB))
71     print "Result = ",oper.GetResult()

里面的case可以参考我另外一篇博客

http://www.cnblogs.com/ListenWind/p/4267517.html

原文地址:https://www.cnblogs.com/ListenWind/p/4625403.html