熱線電話:13121318867

登錄
首頁精彩閱讀Python設計模式之抽象工廠模式
Python設計模式之抽象工廠模式
2018-01-30
收藏

Python設計模式之抽象工廠模式

這篇文章主要為大家詳細介紹了Python設計模式之抽象工廠模式,感興趣的小伙伴們可以參考一下

python面向對象編程入門,我們需要不斷學習進步
"""抽象工廠模式的實現"""    
import random
 
 
class 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 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 "貓糧"
 
 
# 隨機創建合適的工廠
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)

以上就是本文的全部內容,希望對大家的學習有所幫助

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢