《精通Python设计模式》学习之抽象工厂
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《精通Python设计模式》学习之抽象工厂相关的知识,希望对你有一定的参考价值。
这种工厂模式用得少,
可能在游戏类的编程中用得比较多吧。
这个思路清晰一定要OK的。
class Frog: def __init__(self, name): self.name = name def __str__(self): return self.name def interact_with(self, obstacle): print(‘{} the Frog encouners {} and {}!‘.format(self, obstacle, obstacle.action())) 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): print(‘{} the Wizard battles against {} and {}!‘.format(self, obstacle, obstacle.action())) 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 GameEnvironment: def __init__(self, factory): self.hero = factory.make_character() self.obstacle = factory.make_obstacle() def play(self): self.hero.interact_with(self.obstacle) def validate_age(name): try: age = input(‘Welcome {}. How old are you? ‘.format(name)) age = int(age) except ValueError as err: print(‘Age {} is invalid, please try again...‘.format(age)) return (False, age) return (True, age) def main(): name = input("Hello. What‘s your name? ") valid_input = False while not valid_input: valid_input, age = validate_age(name) game = FrogWorld if age < 18 else WizardWorld environment = GameEnvironment(game(name)) environment.play() if __name__ == ‘__main__‘: main()
以上是关于《精通Python设计模式》学习之抽象工厂的主要内容,如果未能解决你的问题,请参考以下文章