Creational – Factory Method
July 25, 2020 2 min read

Factory design pattern is one of the creational design patterns. It defined of an interface or abstract class to create an object and subclasses are responsible to create the instance of the class.
Simply it means, creation of a factory to make objects from the classes. Normally we use constructor to create an object. But in factory method we create a special factory class and through that class we create objects in the classes related to the factory class.
Let’s go with a real world example.

Here I created an interface called Mammal and inside that you can see a method called drinkMilk();. Next in the line 1 and 3, I made 2 classes called Human and Dog (You know Human and Dog are both mammals) by implementing from the Mammal interface and there you can see 2 definitions(methods created) that should be printed in the console in the lines 2 and 4.

Next I created a class called “mammalFactory”. That is the factory where we create mammals. There you can see a method called “getMammal()”. If the user wants to create an object, the only thing that have to do is to call the getMammal() method of class MammalFactory. But at that moment he should pass a String type with the method.
In line 6 says that if the String type you pass with the method is “Human”, it will return new Human object. Or else in line 7 says if the String type you pass with the method is “Dog”, it will return new Dog object.
The advantage of this is when you making those new objects inside the Factory class, you can hide the internal workings of the objects from the user.

In the main method you can see I called the getMammal() method by creating 2 mammal variables and assigning to them. Then by that 2 variables I called the drinkMilk() method in lines 8 and 9. When you run the program you will see the 2 printing commands are printed in the console.
Factory design pattern also known as virtual constructor.
I think you all understood the Factory design pattern well.
Thank you.


