python factory pattern of abstract factory (Abstract Factory)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011510825/article/details/80313048
Abstract Factory pattern 

  It provides a common interface to create multiple interrelated objects.

Abstract factory pattern intended to: provide an interface to the client, you can create multiple product family products object. However, using the abstract factory is conditional:
1. The system has multiple product family, but once the system is only possible where a family of consumer products

2. The products belong to the same family of products used together , the constraints must be reflected in the design of the system. 


Define two classes, Dog and Cat, have speak method

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"

Write an abstract factory class 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()))

During initialization, pass a Dog or Cat, after just an ordinary call is the same. show_pet, the initialization of the incoming class.

    cat_shop = PetShop(Cat)
    cat_shop.show_pet()

The complete code is as follows:

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)


Guess you like

Origin blog.csdn.net/u011510825/article/details/80313048