Core Java

Factory Object Pattern In Java

Introduction:

A Factory Object Pattern comes into picture when having a parent-child class relationship or having an interface based implementation. As the name suggest, the idea is to create a factory class which will be responsible for conditionally instantiating one among the several defined object types.

It promotes loose-coupling by delegating the overhead of instantiating objects to a factory class.

Initial Setup:

Let’s start by defining three classes – Bike (2-wheeler), Car (4-wheeler) and a Truck (6-wheeler), which all implement a common interface – Vehicle:

Each of these classes have an independent implementation of drive() method.  Also for this tutorial, we have assumed our Bike to be 2-wheeler, our Car to be 4-wheeler and our Truck to be a 6-wheeler.

Factory Pattern Implementation In Java:

Now, let’s write our factory class which will return a Vehicle based on say its noOfWheels:

As evident from our implementation, our VehicleFactory’s getVehicle() method returns an object type based on the noOfWheels.

To instantiate various objects, we can now use our factory class:

Isn’t it elegant? That’s the beauty of using a factory class.

Examples of Factory Usage in JDK:

  1. java.util.Calendar.getInstance() method
  2. All wrapper classes expose valueOf() method to return a Wrapper object from a primitive type. Internal implementation of it is based on factory pattern
  3. Class.forName() method
  4. DriverManager.getConnection()

Conclusion:

In this tutorial, we have learned about the Factory Objects and how to implement them in Java.

 

Be the First to comment.

Leave a Comment

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