最近又看了下大話設計模式,決定用Python來試着實現下。html
基礎類設計模式
1 class OperationBase(): 2 """ 3 基礎運算類 4 """ 5 result = 0 6 def GetResult(self): 7 return self.result
繼承類spa
1 class OperationAdd(OperationBase): 2 """ 3 加法類,繼承基礎運算類 4 """ 5 def __init__(self,numA,numB): 6 self.result = numA + numB 7 def GetResult(self): 8 return self.result 9 10 class OperationSub(OperationBase): 11 """ 12 減法運算類,繼承基礎運算類 13 """ 14 def __init__(self,numA,numB): 15 self.result = numA - numB 16 def GetResult(self): 17 return self.result 18 19 class OperationMult(OperationBase): 20 """ 21 乘法運算類,繼承基礎運算類 22 """ 23 def __init__(self,numA,numB): 24 self.result = numA * numB 25 def GetResult(self): 26 return self.result 27 28 class OperationDiv(OperationBase): 29 """ 30 除法運算類,繼承基礎運算類,經過被除數爲0異常捕獲控制被除數不能爲0 31 """ 32 def __init__(self,numA,numB): 33 try: 34 self.result = numA / numB 35 except ZeroDivisionError: 36 print "除數不能爲0!!!" 37 38 def GetResult(self): 39 return self.result 40 41 #工廠類 42 class OperationFactor(): 43 @staticmethod 44 def createOperate(operate,numA,numB): 45 for case in switch(operate): 46 if case('+'): 47 oper = OperationAdd(numA,numB) 48 break 49 if case('-'): 50 oper = OperationSub(numA,numB) 51 break 52 if case('*'): 53 oper = OperationMult(numA,numB) 54 break 55 if case('/'): 56 oper = OperationDiv(numA,numB) 57 break 58 return oper 59 60 if __name__ == '__main__': 61 opt = raw_input("請輸入一個運算操做符(+-*/):") 62 try: 63 numA = float(raw_input("請輸入第一個運算的數字:")) 64 numB = float(raw_input("請輸入第二個運算的數字:")) 65 except ValueError: 66 print "輸入數字不對,請從新輸入!" 67 numA = float(raw_input("請輸入第一個運算的數字:")) 68 numB = float(raw_input("請輸入第二個運算的數字:")) 69 70 oper = OperationFactor.createOperate(opt,float(numA),float(numB)) 71 print "Result = ",oper.GetResult()
裏面的case能夠參考我另一篇博客設計
http://www.cnblogs.com/ListenWind/p/4267517.htmlcode