脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python3设计模式之简单工厂模式

python3设计模式之简单工厂模式

2020-12-11 00:42skadieye Python

这篇文章主要为大家详细介绍了python3设计模式之简单工厂模式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

具体实现见代码:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/skadieye/archive/2017/10/16/7676508.html

延伸 · 阅读

精彩推荐