设计模式(01)-简单工厂模式-Python实现

####最近有一个计划,就是把23种设计模式都实现一遍,弥补一下在这方面的短板。只会curd的程序员不是有梦想的咸鱼。
先贴代码

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
"""
简单工厂模式
实现一个肯德基类
可以生产汉堡
"""
class Foodstuff:
"""食材"""
vegetables = 'vegetables' # 蔬菜
meat = 'meat' # 肉
fruits = 'fruits' # 水果
eggs = 'eggs' # 鸡蛋
class Hamburger:
"""汉堡对象"""
def __init__(self, *args):
j = "".join([i + ' ' for i in args])
self.name = "this is a {} hamburger".format(j)
print("Make a {} burger".format(j))
def __str__(self):
return self.name
class VegetablesMeat(Foodstuff):
"""蔬菜水果汉堡"""
def get_hamburger(self):
return Hamburger(self.vegetables, self.fruits)
class FruitsEggs(Foodstuff):
"""水果鸡蛋汉堡"""
def get_hamburger(self):
return Hamburger(self.fruits, self.eggs)
class KFCFactory:
"""汉堡工厂"""
@staticmethod
def buy_hamburger(hamburger_name):
if hamburger_name == 'vegetables fruits':
return VegetablesMeat()
elif hamburger_name == 'fruits eggs':
return FruitsEggs()
else:
return VegetablesMeat()
if __name__ == '__main__':
vegetables_fruits = KFCFactory.buy_hamburger('vegetables fruits').get_hamburger()
fruits_eggs = KFCFactory.buy_hamburger('fruits eggs').get_hamburger()

坚持原创技术分享,您的支持将鼓励我继续创作!