Understanding factory design pattern
In OOP the term factory means a class that is responsible for creating objects of other types. Clients can call this factory class, with client parameters and object of desired types are created and returned to the client through the factory.
Understanding the factory pattern with a simple example
Let us suppose a factory is responsible to manifacture pens. Their could be many number of types of pens, the factory manifactures. The factory will consist of some departments that handle the manifactures of types of pens. Let us assume Department A produces ball pens & gel pens, and Department B produces ink pens. A client in order to purchase pens first visits the factory and asks for his requirements. The client will be unknown about the departments and the client would not be able to see the manifacture process. The factory provides the client with anytype of pens the client requires. Either the pen could be from department A or deprtment B. But the process of purchase from the clients perspective will be the same for any reqirement they ask for. Only the factory will be respponsible to assign the manifacture either to department A or B.
Benifits Obtained
Logic of the object creation will be hidden
Object creation can be independent of the class implementation
Adding support of new type of object can be easily done.
There are three variants of the Factory Pattern:
1. Simple Factory Pattern
2. Factory Method Pattern
3. Abstract Factory Pattern
Simple Factory Pattern
The factory method pattern
Abstract Factory Pattern
Abstract Factory patterns make sure that the client is isolated from the creation of the objects but allowed to use the objects created. Client will have the ability to access the object only through an interface. If products of one family are to be used, abstract factory pattern helps the client use the object from one/family at a time.
Let us implement the abstract factory pattern with an example.
View the code as well as output in the github source:
https://github.com/kcsanjeeb/Python-design-patterns/blob/master/Factory.ipynb
We will go through facade design pattern pattern in the next topic of design patterns in python.
1 Response
[…] will go through factory design pattern in the next topic of design patterns in […]