python3设计模式之简单工厂模式
2019/7/13 22:45:04
本文主要是介绍python3设计模式之简单工厂模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在Python3环境下,调试实现了《大话设计模式》中简单工厂模式,通过定义单独的工厂类,完成对具体的产品的实例化,参考链接
具体实现见代码:
#!/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 = ''
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。
这篇关于python3设计模式之简单工厂模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门