设计模式学习-简单工厂模式(python3)

参考链接, 在Python3环境下,调试实现了《大话设计模式》中简单工厂模式,通过定义单独的工厂类,完成对具体的产品的实例化

具体实现见代码:

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # Date    : 2017-10-15 21:46:28
 4 # Author  : John
 5 # Version : V1.001
 6 # Func    :
 7 
 8 
 9 class Operator(object):
10     """docstring for Operator"""
11 
12     def __init__(self, NumberA=0, NumberB=0):
13         super(Operator, self).__init__()
14         self.NumberA = NumberA
15         self.NumberB = NumberB
16 
17     def GetResult(self):
18         pass
19 
20 
21 class AddOp(Operator):
22     """docstring for AddOp"""
23 
24     def GetResult(self):
25         return int(float(self.NumberA) + float(self.NumberB))
26 
27 
28 class MinusOp(Operator):
29     """docstring for MinusOp"""
30 
31     def GetResult(self):
32         return int(float(self.NumberA) - float(self.NumberB))
33 
34 
35 class MultiOp(Operator):
36     """docstring for MultiOp"""
37 
38     def GetResult(self):
39         return int(float(self.NumberA) * float(self.NumberB))
40 
41 
42 class DivideOp(Operator):
43     """docstring for DivideOp"""
44 
45     def GetResult(self):
46         try:
47             return float(float(self.NumberA) / float(self.NumberB) * 1.0)
48         except ZeroDivisionError as e:
49             print("DivideOp error, {0}".format(e))
50 
51 
52 class OperatorFactory(object):
53     """docstring for OperatorFactory"""
54 
55     def ChooseOperator(self, op):
56         if op == '+':
57             return AddOp()
58         if op == '-':
59             return MinusOp()
60         if op == '*':
61             return MultiOp()
62         if op == '/':
63             return DivideOp()
64 
65 
66 if __name__ == '__main__':
67     ch = ''
68     while not ch == 'q':
69         NumberA = input('Please input NumberA: ')
70         op = input('Please input operator: ')
71         NumberB = input('Please input NumberB: ')
72 
73         factory = OperatorFactory()
74         opType = factory.ChooseOperator(op)
75         opType.NumberA = NumberA
76         opType.NumberB = NumberB
77 
78         print('The result is: {0}'.format(opType.GetResult()))
79         print('\n#-- input q to exit any key to continue')
80 
81         try:
82             ch = str(input())
83         except Exception as e:
84             print('Get input error: {0}'.format(e))
85             print('Use default value to ch')
86             ch = ''

 

posted @ 2017-10-16 13:05  skadieye  阅读(564)  评论(0编辑  收藏  举报