Skip to content

Instantly share code, notes, and snippets.

@thongnv
Created February 17, 2019 15:47
Show Gist options
  • Save thongnv/78283be09428bc0ce1fb5721a422387b to your computer and use it in GitHub Desktop.
Save thongnv/78283be09428bc0ce1fb5721a422387b to your computer and use it in GitHub Desktop.
import random
class PetShop(object):
"""Cửa hàng thú cưng"""
def __init__(self, animal_factory=None):
"""pet_factory là abstract factory. Chúng ta có thể tuỳ ý lựa chọn pet"""
self.pet_factory = animal_factory
def show_pet(self):
"""Tạo và hiển thị pet bằng abstract factory"""
pet = self.pet_factory()
print("We have a lovely {}".format(pet))
print("It says {}".format(pet.speak()))
class Dog(object):
def speak(self):
return "woof"
def __str__(self):
return "Dog"
class Cat(object):
def speak(self):
return "meow"
def __str__(self):
return "Cat"
# Tạo random animal
def random_animal():
"""Thú cưng được chọn ngẫu nhiên!"""
return random.choice([Dog, Cat])()
# Hiển thị pets với các factory khác nhau
if __name__ == "__main__":
# Shop này chỉ bán mèo
cat_shop = PetShop(Cat)
cat_shop.show_pet()
print("")
# Shop này bán pet ngẫu nhiên
shop = PetShop(random_animal)
for i in range(3):
shop.show_pet()
print("=" * 20)
### OUTPUT ###
# We have a lovely Cat
# It says meow
#
# We have a lovely Dog
# It says woof
# ====================
# We have a lovely Cat
# It says meow
# ====================
# We have a lovely Cat
# It says meow
# ====================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment