Creational Design Patterns: Abstract Factory Pattern

Another Creational Pattern is Abstract Factory Pattern, it is very much similar to Factory Pattern but with more abstraction, it works like a super factory that creates other factory, a use-case of this pattern would be that a Client is suppose to get related objects in a given time, but do not have to know which family until run-time.

Abstract Factory let’s us produce families of related objects without mentioning the concrete class.

Let’s take an example, here at the bakery we bake two types of cake the Usual ones and the Sugar free ones (Variants ), further we  majorly bake for  three occasions, the Birthday cake, wedding cake and the anniversary cake (Family).


If i am looking at simulating this I might have to create individual objects and  map them to their family and variant, that is a lot of work!

So how do I go about solving this problem?

Solution is Abstract Factory  Pattern.

  1. Declare interface for each product in the family <shown below>
  2. Create Abstract Factory (contains all  products in the family)


For each variant we create a separate factory, eg.. A Sugar free cake factory will create only sugar free birthday cake.



Following is the implementation

""" Creational Patterns: Abstract Factory Pattern"""

class BirthdayCake:
    """ One of the objects has to be returned """
    def make_batter(self):
        return "Usual Birthday cake"
    def bake_cake(self):
        return "Baking Usual Cake"

class NoSugarBirthdayCake:
    """ One of the objects has to be returned """

    def make_batter(self):
        return "No sugar Birthday cake"

    def bake_cake(self):
        return "Baking No sugar Cake"

class BirthdayCakeFactory:
    """ Concrete Factory """
    def get_birthday_cake(self):
        """Returns rum cake object """
        return BirthdayCake()

    def get_no_sugar_birthday_cake(self):
        """ Returns fit cake object"""
        return NoSugarBirthdayCake()

class Store:
    """ Houses abstract factory """
    def __init__(self, cake_factory=None):
        self._cake_factory = cake_factory

    def get_bakery_item(self):
        item = self._cake_factory.get_birthday_cake()
        print("The item that is getting baked is --> {}".format(item.bake_cake()))

item = BirthdayCakeFactory()
store = Store(item)

>>The item that is getting baked is --> Baking Usual Cake


Hope that was useful

Stay tuned for more ! Happy Coding

Leave a Reply