【工厂模式】抽象工厂

问题

一个对象的创建,依赖于多个不同的工厂方法,如何使这个对象的创建更容易呢?

工厂方法

将多个工厂方法组合在一起,作为一个抽象工厂

Demo

背景&&需求

根据用户年龄,决定玩儿童游戏(青蛙吃虫子),还是成人游戏(巫师对抗怪物)

代码

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Frog:
def __init__(self, name):
self.name = name

def __str__(self):
return self.name

def interact_with(self, obstacle):
act = obstacle.action()
msg = f'{self} the Frog encounters {obstacle} and {act}!'
print(msg)

class Bug:
def __str__(self):
return 'a bug'

def action(self):
return 'eats it'

# 抽象工厂(创建青蛙、虫子)
class FrogWorld:
def __init__(self, name):
print(self)
self.player_name = name

def __str__(self):
return '------ Frog World ------'

# 工厂方法
def make_character(self):
return Frog(self.player_name)

# 工厂方法
def make_obstacle(self):
return Bug()


class Wizard:
def __init__(self, name):
self.name = name

def __str__(self):
return self.name

def interact_with(self, obstacle):
act = obstacle.action()
msg = f'{self} the Wizard battles against {obstacle} and {act}!'
print(msg)

class Ork:
def __str__(self):
return 'an evil ork'

def action(self):
return 'kills it'


# 抽象工厂(创建巫师、怪物)
class WizardWorld:
def __init__(self, name):
print(self)
self.player_name = name

def __str__(self):
return '------ Wizard World ------'

# 工厂方法
def make_character(self):
return Wizard(self.player_name)

# 工厂方法
def make_obstacle(self):
return Ork()


class Game:
def __init__(self, factory):
self.hero = factory.make_character()
self.obstacle = factory.make_obstacle()

def play(self):
self.hero.interact_with(self.obstacle)

if __name__=="__main__":
name = 'user'
age = int(input('please input age: '))
game = age < 18 and FrogWorld or WizardWorld
Game(game(name)).play()

输出

please input age: 18
—— Wizard World ——
user the Wizard battles against an evil ork and kills it!

please input age: 10
—— Frog World ——
user the Frog encounters a bug and eats it!