The Factory Method Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created. It encapsulates object creation logic in a separate method, promoting loose coupling between the creator and the created objects. This pattern is particularly useful when the exact types of objects to be created may vary or need to be determined at runtime, enabling flexibility and extensibility in object creation.
public abstract class Vehicle {
public abstract void printVehicle();
}
public class TwoWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am two wheeler");
}
}
public class FourWheeler extends Vehicle {
public void printVehicle() {
System.out.println("I am four wheeler");
}
}
public interface VehicleFactory {
Vehicle createVehicle();
}
// Concrete factory class for TwoWheeler
public class TwoWheelerFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new TwoWheeler();
}
}
// Concrete factory class for FourWheeler
public class FourWheelerFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new FourWheeler();
}
}
public class Client {
public static void main(String[] args) {
VehicleFactory twoWheelerFactory = new TwoWheelerFactory();
Vehicle twoWheeler = twoWheelerFactory.createVehicle();
twoWheeler.printVehicle();
VehicleFactory fourWheelerFactory = new FourWheelerFactory();
Vehicle fourWheeler = fourWheelerFactory.createVehicle();
fourWheeler.printVehicle();
}
}