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.
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.
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.
In this tutorial, we have learned about the Factory Objects and how to implement them in Java.