模式設計-----抽象工廠模式

抽象工廠模式(Abstract Factory)屬於建立型工廠模式的一種。python

特色:客戶僅與抽象類定義的接口交互,而不使用特定的具體類的接口。dom

這裏是一個python的例子,運行環境是python 2.7函數

import random

class PetShop:
    """A pet shop"""

    def __init__(self, animal_factory=None):
        self.pet_factory = animal_factory

    def show_pet(self):
        """Create and show a pet using the abstract factory"""
        pet = self.pet_factory.get_pet()
        print("This is a lovely", pet)
        print("It says", pet.speak())
        print("It eats", self.pet_factory.get_food())

class Dog:
    def speak(self):
        return "woof"

    def __str__(self):
        return "Dog"

class Cat:
    def speak(self):
        return "meow"

    def __str__(self):
        return "Cat"

# Factory classes
class DogFactory:
    def get_pet(self):
        return Dog()

    def get_food(self):
        return "dog food"

class CatFactory:
    def get_pet(self):
        return Cat()

    def get_food(self):
        return "cat food"

def get_factory():
    """Let's be dynamic!"""
    return random.choice([DogFactory, CatFactory])()

if __name__ == "__main__":
    factory = PetShop(get_factory())
    for i in range(3):
        factory.show_pet()
        print("="*20)


這裏主要是對抽象工廠進行簡單的學習。學習

這裏主要是經過get_factory函數來進行工廠的選擇。同時每一個真實對象都對應一個工廠類的方式構建code

在每一個新對象建立的時候都要從新定義一個工廠類,這樣使用抽象工廠增長了類的數量,對工程的構建中類的數量帶來必定的麻煩。對象

相關文章
相關標籤/搜索