Factory pattern is one of the most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. Factory design pattern is used when we have a super class with multiple subclasses and based on input, we need to return one of the sub-class. This pattern take out the responsibility of instantiation of a class from client program to the factory class. Super class in factory pattern can be an interface, abstract class or a normal java class.
We will create a Building interface and concrete classes implementing the Building interface. A factory class BuildingFactory is defined as a next step. The demo class, FactoryPatternDemo, will use BuildingFactory to get a Building object. It will pass information (Home / House / Hut) to BuildingFactory to get the type of object it needs. Continue reading “Factory Design Pattern in Java”