本文實例講述了python設計模式之簡單工廠模式。分享給大家供大家參考,具體如下:
簡單工廠模式(simple factory pattern):是通過專門定義一個類來負責創建其他類的實例,被創建的實例通常都具有共同的父類.
下面使用簡單工廠模式實現一個簡單的四則運算
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'andy' ''' 大話設計模式 用任意一種面向對象語言實現一個計算器控制臺程序。要求輸入兩個數和運算符號,得到結果 設計模式——簡單工廠模式 簡單工廠模式(simple factory pattern):是通過專門定義一個類來負責創建其他類的實例,被創建的實例通常都具有共同的父類。 ''' class operation( object ): ''' 四則運算的父類,接收用戶輸入的數值 ''' def __init__( self , number1 = 0 , number2 = 0 ): self .num1 = number1 self .num2 = number2 def getresult( self ): pass pass #加法運算類 class operationadd(operation): def getresult( self ): return self .num1 + self .num2 #減法運算類 class operationsub(operation): def getresult( self ): return self .num1 - self .num2 #乘法運算類 class operationmul(operation): def getresult( self ): return self .num1 * self .num2 #除法運算類 class operationdiv(operation): def getresult( self ): if self .num2 = = 0 : return '除數不能為0 ' return 1.0 * self .num1 / self .num2 #其他操作符類 class operationundef(operation): def getresult( self ): return '操作符錯誤' #簡單工廠類 class operationfactory( object ): def choose_oper( self ,ch): if ch = = '+' : return operationadd() elif ch = = '-' : return operationsub() elif ch = = '*' : return operationmul() elif ch = = '/' : return operationdiv() else : return operationundef() if __name__ = = "__main__" : ch = '' while not ch = = 'q' : num1 = input ( '請輸入第一個數值: ' ) oper = str ( raw_input ( '請輸入一個四則運算符: ' )) num2 = input ( '請輸入第二個數值: ' ) # operation(num1,num2) of = operationfactory() oper_obj = of.choose_oper(oper) oper_obj.num1 = num1 oper_obj.num2 = num2 print '運算結果為: ' ,oper_obj.getresult() |
運行結果:
請輸入第一個數值: 51
請輸入一個四則運算符: -
請輸入第二個數值: 15
運算結果為: 36
這幾個類的結構圖如下:
專門定義一個operation類作為父類,加減乘除運算類繼承operation類,operationfactory類用來決定什么時候創建對應的類
希望本文所述對大家python程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/onepiece-andy/p/python-simple-factory-pattern.html