-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfactory.py
More file actions
55 lines (36 loc) · 896 Bytes
/
factory.py
File metadata and controls
55 lines (36 loc) · 896 Bytes
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
#!/usr/bin/env python
"""
抽象工厂模式
"""
class PetShop:
def __init__(self, animal_factory=None):
self.pet_factory = animal_factory
def show_pet(self):
pet = self.pet_factory.get_pet()
print("动物类型:", str(pet))
print("动物叫声:", pet.speak())
print("吃的东西:", self.pet_factory.get_food())
class Dog:
def speak(self):
return "wang"
def __str__(self):
return "Dog"
class Cat:
def speak(self):
return "miao"
def __str__(self):
return "Cat"
# Factory class
class DogFactory:
def get_pet(self):
return Dog()
def get_food(self):
return "dog food"
class CatFactory:
def get_pet(self):
return Cat()
def get_food(self):
return "cat food"
if __name__ == "__main__":
shop = PetShop(DogFactory())
shop.show_pet()