通過(guò)增加一個(gè)類(工廠類),使得兩個(gè)類(兩部分代碼)解耦,就叫做簡(jiǎn)單工廠設(shè)計(jì)模式。
基類中定義接口,子類中重寫實(shí)現(xiàn),叫做工廠方法模式。
1 class Store(object): #店鋪-基類
2 def select_type(self): #接口
3 pass
4 def order(self, car_type):
5 return self.select_type(car_type)
6
7 class XDStore(Store): #現(xiàn)代4S店
8 def select_type(self, car_type): #實(shí)現(xiàn)
9 return XDFactory().select_car_by_type(car_type)
10 class BMWStore(Store): #寶馬4S店
11 def select_type(self, car_type): #實(shí)現(xiàn)
12 return BMWFactory().select_car_by_type(car_type)
13
14
15 class BMWFactory(object): #寶馬車工廠
16 def select_car_by_type(self, car_type):
17 pass
18 '''
19 if car_type=="mini":
20 return Mini()
21 elif car_type=="720li":
22 return Li720()
23 elif car_type=="X6":
24 return X6()
25 '''
26
27 class XDFactory(object): #現(xiàn)代車工廠
28 def select_car_by_type(self, car_type):
29 if car_type=="索納塔":
30 return Suonata()
31 elif car_type=="名圖":
32 return Mingtu()
33 elif car_type=="ix35":
34 return Ix35()
35
36
37 class Car(object): #車-基類
38 def move(self):
39 print("%s 在移動(dòng)...."%self.name)
40 def music(self):
41 print("%s 正在播放音樂(lè)...."%self.name)
42 def stop(self):
43 print("%s 在停止...."%self.name)
44
45 class Suonata(Car):
46 def __init__(self):
47 self.name = "索納塔"
48
49 class Mingtu(Car):
50 def __init__(self):
51 self.name = "名圖"
52
53 class Ix35(Car):
54 def __init__(self):
55 self.name = "Ix35"
56
57
58 xd_store = XDStore()
59 car = xd_store.order("索納塔")
60 car.move()
運(yùn)行:
索納塔 在移動(dòng)....