Created
March 4, 2016 03:10
-
-
Save drhanlau/4add959e79f301123a5d to your computer and use it in GitHub Desktop.
Code Snippets for Abstract Factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def validate_age(name): | |
try: | |
age = raw_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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Frog: | |
def __init__(self, name): | |
self.name = name | |
def __str__(self): | |
return self.name | |
def interact_with(self, obstacle): | |
print('{} the Frog encounters {} and {}!'.format(self, obstacle, obstacle.action())) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FrogWorld: | |
def __init__(self, name): | |
print(self) | |
self.player_name = name | |
def __str__(self): | |
return '\n\n\t------ Frog World -------' | |
def make_character(self): | |
# return a Frog object here. | |
def make_obstacle(self): | |
# return a bug object here |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def main(): | |
name = raw_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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment