python 工厂模式之abstract factory(抽象工厂)

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)


你可能感兴趣的:(python,架构)