python3设计模式之简单工厂模式
在Python3环境下,调试实现了《大话设计模式》中简单工厂模式,通过定义单独的工厂类,完成对具体的产品的实例化,参考链接
具体实现见代码:
#!/usr/bin/envpython
#-*-coding:utf-8-*-
#Date:2017-10-1521:46:28
#Author:John
#Version:V1.001
#Func:
classOperator(object):
"""docstringforOperator"""
def__init__(self,NumberA=0,NumberB=0):
super(Operator,self).__init__()
self.NumberA=NumberA
self.NumberB=NumberB
defGetResult(self):
pass
classAddOp(Operator):
"""docstringforAddOp"""
defGetResult(self):
returnint(float(self.NumberA)+float(self.NumberB))
classMinusOp(Operator):
"""docstringforMinusOp"""
defGetResult(self):
returnint(float(self.NumberA)-float(self.NumberB))
classMultiOp(Operator):
"""docstringforMultiOp"""
defGetResult(self):
returnint(float(self.NumberA)*float(self.NumberB))
classDivideOp(Operator):
"""docstringforDivideOp"""
defGetResult(self):
try:
returnfloat(float(self.NumberA)/float(self.NumberB)*1.0)
exceptZeroDivisionErrorase:
print("DivideOperror,{0}".format(e))
classOperatorFactory(object):
"""docstringforOperatorFactory"""
defChooseOperator(self,op):
ifop=='+':
returnAddOp()
ifop=='-':
returnMinusOp()
ifop=='*':
returnMultiOp()
ifop=='/':
returnDivideOp()
if__name__=='__main__':
ch=''
whilenotch=='q':
NumberA=input('PleaseinputNumberA:')
op=input('Pleaseinputoperator:')
NumberB=input('PleaseinputNumberB:')
factory=OperatorFactory()
opType=factory.ChooseOperator(op)
opType.NumberA=NumberA
opType.NumberB=NumberB
print('Theresultis:{0}'.format(opType.GetResult()))
print('\n#--inputqtoexitanykeytocontinue')
try:
ch=str(input())
exceptExceptionase:
print('Getinputerror:{0}'.format(e))
print('Usedefaultvaluetoch')
ch=''
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。