通过增加一个类(工厂类),使得两个类(两部分代码)解耦,就叫做简单工厂设计模式。
基类中定义接口,子类中重写实现,叫做工厂方法模式。
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): #现代4S店
8 def select_type(self, car_type): #实现
9 return XDFactory().select_car_by_type(car_type)
10 class BMWStore(Store): #宝马4S店
11 def select_type(self, car_type): #实现
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): #现代车工厂
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 在移动...."%self.name)
40 def music(self):
41 print("%s 正在播放音乐...."%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()
运行:
索纳塔 在移动....
网友评论