摘要:python面向?qū)ο缶幊倘腴T,我們需要不斷學(xué)習(xí)進步"""抽象工廠模式的實現(xiàn)"""import random class PetShop: """寵物商店""" de
python面向?qū)ο缶幊倘腴T,我們需要不斷學(xué)習(xí)進步
"""抽象工廠模式的實現(xiàn)"""
import random class PetShop: """寵物商店""" def __init__(self, animal_factory=None): """寵物工廠是我們的抽象工廠。我們可以隨意設(shè)置。""" self.pet_factory = animal_factory def show_pet(self): """使用抽象工廠創(chuàng)建并顯示一個寵物""" pet = self.pet_factory.get_pet() print("我們有一個可愛的 {}".format(pet)) print("它說 {}".format(pet.speak())) print("我們還有 {}".format(self.pet_factory.get_food())) # 工廠生產(chǎn)的事物 class Dog: def speak(self): return "汪" def __str__(self): return "Dog" class Cat: def speak(self): return "喵" def __str__(self): return "Cat" # Factory classes class DogFactory: def get_pet(self): return Dog() def get_food(self): return "狗食" class CatFactory: def get_pet(self): return Cat() def get_food(self): return "貓糧" # 隨機創(chuàng)建合適的工廠 def get_factory(): """讓我們動起來!""" return random.choice([DogFactory, CatFactory])() # 多個工廠顯示寵物 if __name__ == "__main__": for i in range(4): shop = PetShop(get_factory()) shop.show_pet() print("=" * 20)
結(jié)果如圖:
更多關(guān)于Python設(shè)計模式之抽象工廠模式請關(guān)注PHP中文網(wǎng)(www.miracleart.cn)其他文章!