亲宝软件园·资讯

展开

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

skadieye 人气:0
想了解python3设计模式之简单工厂模式的相关内容吗,skadieye在本文为您仔细讲解python3简单工厂模式的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,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 = ''

加载全部内容

相关教程
猜你喜欢
用户评论