Creational Design Patters – Factory Pattern

Let begin with a scenario

I own a Bakery and I am only selling cakes, last Christmas I had a pretty good sale, customers and family friends gave good review on various flavors of cakes, especially Rum cake – it was a hit ! and the I thought to myself why not try selling other bakery items Breads, muffins, etc to expand the varieties my bakery.

Creational Patterns is all about the mechanism of creating objects in a controlled and uncomplicated manner.

Clearly, to do something like this I would need to setup my kitchen for bread baking, lets call it Concrete Class for bread in our code, I would be instantiated(create objects ) Bread class at the run time thereby giving a bread object, also keep in mind I already have a cake class available in my code. But how do I know which object will be instantiated  bread/cake? How do I go about handling this?

One of the best practices to use when you do not know what type of objects you will be needing eventually in your system is Factory Pattern.

Factory pattern encapsulates object creation i.e.. Factory is an object specializing in creating other objects. It should be used when the system needs to decide  what class to use at run-time. Here is an example of implementing a Factory Pattern.

Here is a code snippet, we have a concrete class called ‘Cake’ and another one called ‘Bread’. The function get_item is a factory method.

""" Creational Patterns"""


class Cake:
    """ Concrete Class for the cakes """
    def __init__(self,item_name):
        self._item_name = item_name

    def item_baked(self):
        return "Cake"


class Bread:
    """ Concrete Class for the cakes """
    def __init__(self,item_name):
        self._item_name = item_name

    def item_baked(self):
        return "Bread"


def get_item(cake='cake'):
    """ Factory Function """
    item = dict(
        cake=Cake("Rum Cake"), 
        bread=Bread("Multigrain Bread")
    )
    return item[cake]


obj = get_item('bread')
print('Item type -->{}'
      .format(obj.item_baked())
      )

>>Multigrain Bread,Bread

get_item Factory method creates objects for the concrete class and at run-time we can have either bread or cake objects available.

Try running this code, and see for your self how it works. Hope this was fun ! stay tuned in for the next discussion on Abstract Factory.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s