Factory pattern in Python

We use design pattern to build reusable solution. Building reusable solution is hard and design patterns helps us by giving common design solution for same sort of problems.

One of the important design patterns is Factory Method Pattern. In Python the implementation of factory pattern look like below:

class Ladder(object):
def __init__(self):
self.hight = 20
class Table(object):
def __init__(self):
self.legs = 4
my_factory = {
"target1": Ladder,
"target2": Table,
if __name__ == '__main__':
print my_factory ["target1"]().hight

When to use factory pattern?

There are couple of cases when we can use factory pattern, one of the case is- when there is needed to create objects that are dependent on other objects.

That means when we are going to create a complex objects, and complex objects will be based on other objects. When we need to create the complex object we dont need to know the details about other objects that rely on the creation process. Example is like below:

class Train(object):
def __init__(self):
self.speed = 120
class Bus(object):
def __init__(self):
self.speed = 60
class Trum(object):
def __init__(self):
self.speed = 40
class System(object):
def create(self, *args):
return args
class TranspotationSystem(object):
def __init__(self):
self.train = Train()
self.bus = Bus()
self.trum = Trum()
def createTSSyetm(self):
s = System()
t_system = s.create(self.train, self.trum, self.bus)
for t in range(0,len(t_system)):
print t_system[t].speed
if __name__=='__main__':
T = TranspotationSystem()
t = Train()
tr = Trum()
b = Bus()

Ideal situation would be, when we see we are coding to gather information to create objects. And factories help to gather object creation in a single place. And also it helps to create decoupled system.

If you have better understanding and experience of using factory pattern in your python code, please share it in comment.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.