Factory pattern is a creational pattern. It defines an interface for creating different type of object on the run-time. Enough jargon! let’s see an example.
Imagine you are have created a motorbike sharing app. As days gone by, your app become so much popular that users are also requesting to enable car sharing too!
Though you are happy and enjoying the excitement of upcoming success, but what about the code? Right now your code has only Bike class, and all the other methods and classes are intertwined with this class. If you need to add another class like Car you will require huge refactoring. What if you need to add another service like Drone in future too?
Here comes Factory pattern in rescue. It suggests that instead of direct instantiation of objects use a factory method to instantiate similar kind of object. Just keep in mind that the objects returned by the factory methods are called products.
Let’s see how does it looks in code:
Here we created a interface called TransportInterface it just contains the blueprints of methods in our case it is a single method called giveRide.
Two other classes Car and Bike implements this TransportInterface and its method. Now let’s see how the factory going to look like:
Using the decorator @staticmethod enables us to by pass instantiation of a class to use a method. It’s use us pretty simple, when we need a car we just do this:
>>> car = TransportFactory.getTransport("car")
Give ride by car
As here the example is too much simple it might not seem that the extra pain to create a factory worth it. But, in cases when instantiation of classes require some more logic and codes and if the classes are similar, then all the complexity if creation can be hidden by using factory pattern which in the long run helps to develop manageable codebase. There might be cases when you need to change the business logic in class instantiation, if you do not use factory, you will be required to change the logic in every where you wrote those logic, but if you use factory, you just have to update the factory, and the other things will feel like breeze!!!