Learn How To Implement The Popular Factory Design Pattern in Java

0
2775
Factory Design Pattern

Factory Design Pattern

In the last chapter, we discussed about the overview, concepts, application and categorization of various Design Patterns which obey standardized coding practice and help novice developers learn about the software design very swiftly within no time. In this chapter, we are going to discuss about Factory Pattern, which is one of the most commonly used design patterns in Java/J2EE. It falls under the category of creational design pattern as this pattern help us provide a common and very simple way to create objects and hide the actual creation logic.

In Factory design pattern, an object is created without exposing the actual creation logic to the client and with the help of a common interface reference can be made to a newly created object.

Implementation of Factory design pattern
To understand the design pattern, we are going to create a Vehicle interface and concrete classes (i.e., Car, Bike and Truck classes) which implement the Vehicle interface. A factory class VehicleFactory is defined in the next step.

The FactoryDesignPattern class will use the VehicleFactory class to get a Vehicle object. It will pass information (i.e. CAR / BIKE / TRUCK) to VehicleFactory to get the type of object it needs.

Vehicle object

Step 1: – Creation of an interface i.e. Vehicle.java

Step 2: – Creation of the three concrete classes (i.e., Car, Bike and Truck classes) which implements the same interface i.e. Vehicle.java
Car.java

Bike.java

Truck.java

Step 3: – Creation of a Factory in order to generate object of concrete class based on the given information.
VehicleFactory.java

Step 4: – Creation of FactoryDesignPattern class in order to use the Factory to get an object of the concrete class by simply passing an information such as type.
FactoryDesignPattern.java

Step 5: – When we execute FactoryDesignPattern class as a Java application, then will observe the following desired output which demonstrate the Factory design pattern.

Source code for the design pattern in java

Conclusion: –
In this chapter, we discussed the factory design pattern in detail along with a suitable example. In that example, we have demonstrated the step by step creation of Interface, concrete classes, factory class and Factory design implementer class.

LEAVE A REPLY

Please enter your comment!
Please enter your name here