Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 641
teddybear123 Avatar asked Jan 31 '17 04:01

teddybear123


People also ask

What is Abstract Factory design pattern in Python?

Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects.

What are the advantages of using Abstract Factory pattern in Python?

The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes. Clients manipulate instances through their abstract interfaces.

When would you use the Abstract Factory pattern?

When to Use Abstract Factory Pattern: The client is independent of how we create and compose the objects in the system. The system consists of multiple families of objects, and these families are designed to be used together. We need a run-time value to construct a particular dependency.

Is factory pattern useful in Python?

The “Factory Method” pattern is a poor fit for Python. It was designed for underpowered programming languages where classes and functions can't be passed as parameters or stored as attributes.


1 Answers

There are two main benefits of the Abstract Factory pattern:

1) Decouple the client code

The point of the Abstract Factory pattern is to decouple the client (in this case PetStore) from the concrete classes it creates (in this case Dog).

Image you had a different family of pets - cats, for example. Using the Abstract factory pattern, you can create a different factory that produces Cat objects. The key insight here is that both factories share the same interface - i.e. get_pet() and get_food():

class Cat:
    def speak(self): return "Meow!"
    def __str__(self): return "Cat"

class CatFactory:
    def get_pet(self): return Cat()
    def get_food(self): return "Cat Food!"

Now, because of the common interface between factories, you only need to chance one line of code to have the client act on cats instead of dogs:

factory = CatFactory()

The PetStore class itself does not need to be changed.

2) Enforce a relationship between a family of related classes

You could argue that, instead of passing in a DogFactory or CatFactory, why not just pass in a Dog or a Cat? And this is where your example code fails to show the power of the Abstract Factory pattern. The pattern really shines when there is a whole family of related classes that go together. In your example, there is only the dog itself, and the dog food. But imagine you also had a dog bed, a dog collar, a dog toy, etc. If this were the case, and you were not using the Abstract Factory pattern, then you might write code like this:

pet = Dog()
food = DogFood()
bed = DogBed()
collar = DogCollar()
toy = DogToy()

shop = PetStore(pet, food, bed, collar, toy)

This code is verbose and inflexible. There also is a danger that you might accidentally pass a cat toy in with dog products.

Instead, using an AbstractFactory, the code becomes trivial and the relationship between the families of classes is enforced:

factory = DogFactory()
shop = PetStore(factory)  # PetStore calls get_*(), and is guaranteed
                          # to only get dog products
like image 169
Lee Netherton Avatar answered Sep 18 '22 12:09

Lee Netherton