python 工廠模式之abstract factory(抽象工廠)
阿新 • • 發佈:2019-01-07
Abstract Factory模式
提供一個共同的介面來建立相互關聯的多個物件。
抽象工廠模式的用意為:給客戶端提供一個介面,可以建立多個產品族中的產品物件。 不過使用抽象工廠是有條件的:
1.系統中有多個產品族,而系統一次只可能消費其中一族產品
2.同屬於同一個產品族的產品在一起使用,這一約束必須在系統的設計中體現出來。
定義兩個類,Dog和Cat,都擁有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"
寫一個抽象工廠類PetShop.
class PetShop(object): """A pet shop""" def __init__(self, animal_factory=None): """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def show_pet(self): """Creates and shows a pet using the abstract factory""" pet = self.pet_factory() print("We have a lovely {}".format(pet)) print("It says {}".format(pet.speak()))
初始化時,傳一個Dog 或者 Cat,之後就跟普通的呼叫是一樣的。show_pet中,初始化傳入的類。
cat_shop = PetShop(Cat)
cat_shop.show_pet()
完整程式碼如下:
import random class PetShop(object): """A pet shop""" def __init__(self, animal_factory=None): """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def show_pet(self): """Creates and shows a pet using the 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" # Additional factories: # Create a random animal def random_animal(): """Let's be dynamic!""" return random.choice([Dog, Cat])() # Show pets with various factories if __name__ == "__main__": # A Shop that sells only cats cat_shop = PetShop(Cat) cat_shop.show_pet() print("") # A shop that sells random animals shop = PetShop(random_animal) for i in range(3): shop.show_pet() print("=" * 20)