![]() |
VOOZH | about |
Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the client, and for creating the new type of object, the client uses the same common interface.
Imagine you are having your own startup which provides ridesharing in different parts of the country. The initial version of the app only provides Two-Wheeler ridesharing but as time passes, your app becomes popular and now you want to add Three and Four-Wheeler ridesharing also.
It's a piece of great news! but what about the software developers of your startup. They have to change the whole code because now most part of the code is coupled with the Two-Wheeler class and developers have to make changes to the entire codebase.
After being done with all these changes, either the developers end with the messy code or with the resignation letter.
Diagrammatic representation of Problems without using Factory Method
Let's understand the concept with one more example which is related to the translations and localization of the different languages.
Suppose we have created an app whose main purpose is to translate one language into another and currently our app works with 10 languages only. Now our app has become widely popular among people but the demand has grown suddenly to include 5 more languages.
It's a piece of great news! only for the owner not for the developers. They have to change the whole code because now most part of the code is coupled with the existing languages only and that's why developers have to make changes to the entire codebase which is really a difficult task to do.
Let's look at the code for the problem which we may face without using the factory method.
Note: Following code is written without using the Factory method.
Its solution is to replace the straightforward object construction calls with calls to the special factory method. Actually, there will be no difference in the object creation but they are being called within the factory method.
For example Our Two_Wheeler, Three_Wheeler, and Four_wheeler classes should implement the ridesharing interface which will declare a method called a ride. Each class will implement this method uniquely.
Now let us understand the factory method with the help of an example:
Let's look at the class diagram considering the example of ride-sharing.