When we want to return one sub-class object from multiple sub-classes using an input, should use Factory design pattern. Factory class takes responsibility of instantiation the class (We can return Singleton instance from static factory method).
In Factory pattern, we create an object without exposing the creation logic to the client and refer to a newly created object using a common interface.
Coffee/Vending machine, give input from options and as per input coffee, lemon tea, plain milk or hot water will be an output.
Benefits of Factory Method Pattern:
Factory Method Pattern provides an approach to code for interface rather than implementation and it provides the abstraction between implementation and client classes through inheritance.
Factory Method Pattern allows the sub-classes to choose the type of objects to create. We can easily change the implementation of sub-class because client program is unaware of this. It makes the code more robust, less coupled and easy to extend (client interacts solely with the resultant interface or abstract class).
Usage in JDK:
java.util.Calendar, ResourceBundle and NumberFormat getInstance() methods uses Factory pattern.
valueOf() method in wrapper classes like Boolean, Integer etc.
Spring and Hibernate frameworks.