Factory Design Pattern: Simplifying Object Creation

The Factory Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It is useful when you want to decouple object creation logic from the main logic of your application.

Why Use the Factory Pattern?

  • Flexibility: Allows you to create objects without specifying their exact class.

  • Decoupling: Separates object creation logic from the main logic.

  • Extensibility: Makes it easy to add new types of objects without modifying existing code.

Example: Creating Different Types of Vehicles

Let’s say you’re building a vehicle manufacturing system. You want to create different types of vehicles (e.g., cars, bikes, trucks) without hardcoding the creation logic in your main application. The Factory Pattern can help you achieve this.

Step-by-Step Implementation

Step 1: Create the Vehicle Interface

This interface defines the common behavior for all vehicles.

public interface Vehicle {
    void drive();
}

Step 2: Create Concrete Vehicle Classes

Implement the Vehicle interface for different types of vehicles.

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

public class Bike implements Vehicle {
    @Override
    public void drive() {
        System.out.println("Riding a bike...");
    }
}

public class Truck implements Vehicle {
    @Override
    public void drive() {
        System.out.println("Driving a truck...");
    }
}

Step 3: Create the VehicleFactory Class

This class decides which type of vehicle to create based on the input.

public class VehicleFactory {
    public static Vehicle getVehicle(String type) {
        if (type.equalsIgnoreCase("car")) {
            return new Car();
        } else if (type.equalsIgnoreCase("bike")) {
            return new Bike();
        } else if (type.equalsIgnoreCase("truck")) {
            return new Truck();
        }
        throw new IllegalArgumentException("Invalid vehicle type: " + type);
    }
}

Step 4: Use the Factory to Create Vehicles

Now, you can use the VehicleFactory to create different types of vehicles without knowing their exact class.

public class Main {
    public static void main(String[] args) {
        // Create a car using the factory
        Vehicle car = VehicleFactory.getVehicle("car");
        car.drive();

        // Create a bike using the factory
        Vehicle bike = VehicleFactory.getVehicle("bike");
        bike.drive();

        // Create a truck using the factory
        Vehicle truck = VehicleFactory.getVehicle("truck");
        truck.drive();
    }
}

Output

Driving a car...
Riding a bike...
Driving a truck...

Key Points About the Factory Pattern

  1. Decoupling: The factory hides the object creation logic from the client.

  2. Single Responsibility: The factory class is responsible for creating objects, making the code easier to maintain.

  3. Extensibility: You can add new types of objects by simply extending the factory.

Real-Life Analogy

Think of the Factory Pattern like a car dealership. You don’t need to know how a car is manufactured; you just tell the dealership what type of car you want, and they provide it. Similarly, the factory creates objects for you based on your requirements.

When to Use the Factory Pattern?

  • When you want to decouple object creation logic from the main logic.

  • When you need to create objects dynamically at runtime.

  • When you want to centralize object creation logic for better maintainability.

1
Subscribe to my newsletter

Read articles from Niharika Maruvada directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Niharika Maruvada
Niharika Maruvada

JAVA Developer Passionate about crafting innovative and efficient solutions in the FinTech industry, I thrive on building cutting-edge applications that solve real-world problems. With a strong focus on clean, scalable, and maintainable code, I aim to drive business success through technology. Always eager to embrace new challenges and expand my skill set, I am committed to staying at the forefront of emerging technologies and best practices. My dedication to continuous learning and professional growth fuels my ability to deliver impactful results. Let’s connect and build the future of FinTech together! #Java #FinTech #Innovation #CleanCode #TechEnthusiast #ContinuousLearning