Thursday, March 9, 2023

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++.

Symbian Active Object framework...




Then when i switched over to Android, I started studying the Android framework code.

For example here are two such detailed study analyses on Asynctask and Android Service Framework


Asynstask Framework...




Android Service internals...




This has changed my mindset from looking at code from just a programmer's perspective. I try to find out the design principles and try to join the invisible dots inside the framework code.

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 makefood(self,type):

       if(type == "ch"):

           return Chocolate()

       if(type == "bi"):

           return Biscuit()

if __name__ == '__main__':

   fact = Factory()

   chocolate = fact.makefood("ch")

   biscuit = fact.makefood("bi")



Friends... Enjoy...
Just start deciphering a framework code...
And become happy in your endeavor...

No comments: