Factory Pattern in Python...

I used to get the utmost satisfaction by deciphering framework code. I remember, initially, I used to study the MFC framework code and came to know about observer patterns, about the chain of responsibility design patterns being used there.
Later, I used to study the Symbian S60 framework code - and studied in detail their Active Object design principles and ECom plugins.
Yes, I am talking about 2006-2007 just before the arrival of the iPhone and Android when NOKIA was the undisputed leader in the mobile world.
Please have a look at the following blog post where I deciphered the basic Active Object of the Symbian framework and why a long-running task does not freeze the UI.
So the point is, don't blindly follow anything. Keep your inquisitive mind always ready for new stuff. For example, my inquisition about the two-phase constructor in Symbian led me to study the Boost library in 2007 in Japan which ultimately became part of the C++ standard library in the 2009 release of C++.
For example, when i found the parameterized factory pattern implementation in the Android framework code, my vision becomes clearer than the vision of a programmer.
Please have a look at the following document where i studied that part of the Android media framework where the parameterized factory pattern is used.
So, here we go - an implementation of Factory Pattern in Python.
from abc import ABC, abstractmethod
class Food(ABC):
pass
class Chocolate(Food):
def __init__(self):
print("chocolate is made")
class Biscuit(Food):
def __init__(self):
print("biscuit is made")
class Factory:
def make_food(self, type):
if type == "ch":
return Chocolate()
if type == "bi":
return Biscuit()
if __name__ == '__main__':
fact = Factory()
chocolate = fact.make_food("ch")
biscuit = fact.make_food("bi")
This code defines an abstract base class Food
and two subclasses Chocolate
and Biscuit
. The Factory
class has a method make_food
that creates instances of Chocolate
or Biscuit
based on the input type. The if __name__ == '__main__':
block demonstrates how to use the factory to create these objects.
Friends... Enjoy...
Just start deciphering a framework code...
And become happy in your endeavour...
Subscribe to my newsletter
Read articles from Somenath Mukhopadhyay directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Somenath Mukhopadhyay
Somenath Mukhopadhyay
To win is no more than this... To rise each time you fall...