Factory Design Pattern in Java

Introduction

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.

Implementation

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.

Class Diagram

Factory Pattern in JEE
The following steps illustrate how to create factory pattern

Step 1. Create a Building interface. This interface has only one method build() which will be implemented by different classes to build different kind of buildings.

Step 2. Create concrete classes to implement the Building interface.

The below class builds a Home.

The below class builds a House.

The below class builds a Hut.

Step 3. Create a BuildingFactory to generate object of concrete class based on given information.

Step 4. Use the BuildingFactory to get object of concrete class by passing an information such as building type.

Step 5. Run FactoryPatternDemo. You will see the below output

Advantages

Factory pattern provides approach to code for interface rather than implementation.
Factory pattern removes the instantiation of actual implementation classes from client code, making it more robust, less coupled and easy to extend.
Factory pattern provides abstraction between implementation and client classes through inheritance.

That’s all. Thank you for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.