首頁  >  文章  >  後端開發  >  python3之簡單工廠模式的介紹

python3之簡單工廠模式的介紹

黄舟
黄舟原創
2017-10-17 10:23:402068瀏覽

這篇文章主要為大家詳細介紹了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 pideOp(Operator):
 """docstring for pideOp"""

 def GetResult(self):
 try:
  return float(float(self.NumberA) / float(self.NumberB) * 1.0)
 except ZeropisionError as e:
  print("pideOp 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 pideOp()


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之簡單工廠模式的介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn