python面向?qū)ο缶幊倘腴T(mén),我們需要不斷學(xué)習(xí)進(jìn)步
"""抽象工廠(chǎng)模式的實(shí)現(xiàn)"""
import randomclass PetShop: """寵物商店""" def __init__(self, animal_factory=None): """寵物工廠(chǎng)是我們的抽象工廠(chǎng)。我們可以隨意設(shè)置。""" self.pet_factory = animal_factory def show_pet(self): """使用抽象工廠(chǎng)創(chuàng)建并顯示一個(gè)寵物""" pet = self.pet_factory.get_pet() print("我們有一個(gè)可愛(ài)的 {}".format(pet)) print("它說(shuō) {}".format(pet.speak())) print("我們還有 {}".format(self.pet_factory.get_food()))# 工廠(chǎng)生產(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 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 "貓糧"# 隨機(jī)創(chuàng)建合適的工廠(chǎng)def get_factory(): """讓我們動(dòng)起來(lái)!""" return random.choice([DogFactory, CatFactory])()# 多個(gè)工廠(chǎng)顯示寵物if __name__ == "__main__": for i in range(4): shop = PetShop(get_factory()) shop.show_pet() print("=" * 20)結(jié)果如圖:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注