[13614 views]
The Factory Design Pattern is a part of Creational Design Patterns and what it describes is a generic way for creating objects and initializing it. It is commonly implemented as a function or method which is used to generate other objects.
The key concept of the Factory pattern is to abstract the way an object or a group of related objects are created and instantiated for a specific purpose. The point of this abstraction is to avoid coupling an implementation with particular classes or the way that each object instance should be created and configured. The outcome is an implementation that functions as an abstract way for object creation and initialization, which in turn follows the concept of Separation of Concerns.
In simple terms, One class acts as a Factory class, which is a singleton class, it acts as the Object creator for another class. For example, CarFactory creates many Car objects.
In the above code, we have created two java Files, CarFactory.java and Car.java
CarFactory.java is the code which acts as a Factory Class as it has method newCar() to create an object of Car Class. As you have noticed, CarFactory Class itself is a singleton Class,(For more information on Singleton Pattern, visit here) so there would be only one CarFactory object.
If you want to create an object of Car, you will have to use CarFactory Class instance and call newCar() method of CarFactory to create an instance of Car which returns a Car object.
In above File, FactoryDemo.java which has main method, we first fetched the instance of CarFactory Class and then using CarFactory object we created a new Car instance by calling newCar() method i.e in above example "Car audi=carFactory.newCar();".
If you still have any doubts about Factory Design Pattern, please leave a comment. We will be happy to discuss it with you.