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:

interface Vehicle {
    void drive();
}

public class Bike implements Vehicle {
    public void drive(){  System.out.println("Driving Bike"); }
}

public class Car implements Vehicle {
    public void drive(){  System.out.println("Driving Car"); }
}

public class Truck implements Vehicle {
    public void drive(){  System.out.println("Driving 6-wheeler Truck"); }
}

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:

public class VehicleFactory {
    public static Vehicle getVehicle(int noOfWheels) {
        Vehicle vehicle = null;
        switch(noOfWheels) {
            case 2 : vehicle = new Bike(); break;
            case 4 : vehicle = new Car(); break;
            case 6 : vehicle = new Truck(); break;
        }
        return vehicle;
    }
}

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:

Vehicle vehicle = VehicleFactory.getVehicle(2);
System.out.println(vehicle.drive()); //prints "Driving Bike"

vehicle = VehicleFactory.getVehicle(4);
System.out.println(vehicle.drive()); //prints "Driving Car"

vehicle = VehicleFactory.getVehicle(6);
System.out.println(vehicle.drive()); //prints "Driving 6-wheeler Truck"

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.

 

One comment
Pingback: Factory Method Design Pattern

Leave a Comment

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