码迷,mamicode.com
首页 > 其他好文 > 详细

抽象工厂设计模式

时间:2019-11-30 19:23:20      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:bst   bug   统一   player   pre   str   orm   使用方法   具体类   

 1 class Frog:
 2     def __init__(self,name):
 3         self.name = name
 4 
 5     def __str__(self):
 6         return self.name
 7 
 8     def interact_with(self,obstacle):
 9         print(‘{} the frog encounters {} and {}‘.format(self,obstacle,obstacle.action()))
10 
11 class Bug():
12     def __str__(self):
13         return ‘a bug‘
14 
15     def action(self):
16         return ‘eats it‘
17 
18 class FrogWorld():
19     def __init__(self,name):
20         print(self)
21         self.player_name = name
22 
23     def __str__(self):
24         return ‘\n\n\t--------- frog world ---------25 
26     def make_character(self):
27         return Frog(self.player_name)
28 
29     def make_obstacle(self):
30         return Bug()
31 
32 class Wizard():
33     def __init__(self,name):
34         self.name = name
35     def __str__(self):
36         return self.name
37 
38     def interact_with(self,obstacle):
39         print(‘{} the Wizard battles against {} and {}!‘.format(self,obstacle,obstacle.action()))
40 
41 class Ork:
42     def __str__(self):
43         return ‘an evil ork‘
44     def action(self):
45         return ‘kill it‘
46 
47 class WizardWorld:
48     def __init__(self,name):
49         print(self)
50         self.player_name = name
51 
52     def __str__(self):
53         return ‘\n\n\t------- Wizard World -------54 
55     def make_character(self):
56         return Wizard(self.player_name)
57 
58     def make_obstacle(self):
59         return Ork()
60 
61 class GameEnvironment:
62     def __init__(self,factory):
63         self.hero = factory.make_character()
64         self.obstacle = factory.make_obstacle()
65 
66     def paly(self):
67          self.hero.interact_with(self.obstacle)
68 
69 def validate_age(name):
70     try:
71         age = input(‘welcome {} .how old are you? ‘.format(name))
72         age = int(age)
73     except ValueError as err:
74         print(‘Age {} is invalid, please try again .....‘.format(age))
75         return (False,age)
76     return (True,age)
77 
78 def main():
79     name = input("hello,what‘your name?")
80     valid_input = False
81     while not valid_input:
82         valid_input, age = validate_age(name)
83     game = FrogWorld if age < 18 else WizardWorld
84     environment = GameEnvironment(game(name))
85     environment.paly()
86 
87 if __name__ == ‘__main__‘:
88     main()

 

抽象工厂设计模式与工厂方法在形式上最大的区别在于抽象工厂会设计生成一个抽象类(实际上类似提供一个接口,对底层实现的具体类进行封装后隐藏,提供统一的使用方法)

抽象工厂设计模式

标签:bst   bug   统一   player   pre   str   orm   使用方法   具体类   

原文地址:https://www.cnblogs.com/kaiseryin/p/11963345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!