python面向對象編程入門,我們需要不斷學習進步
"""抽象工廠模式的實現"""
import randomclass PetShop: """寵物商店""" def __init__(self, animal_factory=None): """寵物工廠是我們的抽象工廠。我們可以隨意設置。""" self.pet_factory = animal_factory def show_pet(self): """使用抽象工廠創建并顯示一個寵物""" pet = self.pet_factory.get_pet() print("我們有一個可愛的 {}".format(pet)) print("它說 {}".format(pet.speak())) print("我們還有 {}".format(self.pet_factory.get_food()))# 工廠生產的事物class Dog: def speak(self): return "汪" def __str__(self): return "Dog"class Cat: def speak(self): return "喵" def __str__(self): return "Cat"# Factory classesclass 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 "貓糧"# 隨機創建合適的工廠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)結果如圖:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選