lundi 30 janvier 2017

trying to make sense of abstract factory pattern in Python

I found this example of abstract factory pattern in Python. I'm trying to make sense of why there needs to be a DogFactory, wouldn't it be lesser code just call the Dog class, can someone explain as to how this pattern will be useful in a real world application

class Dog:

    def speak(self):
        return "Woof!"

    def __str__(self):
        return "Dog"


class DogFactory:

    def get_pet(self):
        return Dog()

    def get_food(self):
        return "Dog Food!"


class PetStore:

    def __init__(self, pet_factory=None):

        self._pet_factory = pet_factory


    def show_pet(self):

        pet = self._pet_factory.get_pet()
        pet_food = self._pet_factory.get_food()

        print("Our pet is '{}'!".format(pet))
        print("Our pet says hello by '{}'".format(pet.speak()))
        print("Its food is '{}'!".format(pet_food))

factory = DogFactory()

shop = PetStore(factory)

shop.show_pet()

Aucun commentaire:

Enregistrer un commentaire