Blog Design Pattern

The Factory Method Pattern: The Ultimate Guide to Creating Objects

Introduction

The Factory Method Pattern is a creational design pattern that provides an interface for creating objects in a super-class, while allowing sub-classes to alter the type of objects that will be created. In simpler terms, it allows you to create objects without exposing the creation logic to the client code, deferring the instantiation to sub-classes.

What is the Factory Method Pattern?

The Factory Method Pattern consists of the following components:

  1. Product Interface: Defines the interface of objects that the factory method creates.
  2. Concrete Product: Implements the Product interface and represents the actual objects being created.
  3. Creator: Declares the factory method, which returns an object of type Product. The Creator class may also define a default implementation of the factory method.
  4. Concrete Creator: Overrides the factory method to return an instance of a Concrete Product.

Advantages of the Factory Method Pattern

The Factory Method Pattern offers several benefits:

  1. Product Creation Logic Encapsulation: The creation logic is encapsulated in the factory method, making it easy to change the implementation or introduce new products without modifying the client code.
  2. Product Subclass Selection: Subclasses can override the factory method to return different types of products.
  3. Loose Coupling: The client code is decoupled from the concrete product classes, promoting loose coupling and easier maintenance.
  4. Parallel Class Hierarchies: The pattern supports creating parallel class hierarchies for products and creators, making it easier to add new products or creators.

Use Cases

The Factory Method Pattern is commonly used in the following scenarios:

  1. When you need to create objects of different subclasses based on certain conditions or configurations.
  2. When the creation process involves complex logic that should be encapsulated and reused across multiple products.
  3. When you want to provide a library of products without exposing the implementation details.

Java Example

Let’s illustrate the Factory Method Pattern with a Java example. Consider a scenario where we have different types of transportation vehicles, and we want to create them based on the user’s preference.

Java
// Product Interface
interface Vehicle {
    void drive();
}

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

class Motorcycle implements Vehicle {
    public void drive() {
        System.out.println("Riding a motorcycle.");
    }
}

// Creator
abstract class VehicleFactory {
    public abstract Vehicle createVehicle();

    public void manufactureVehicle() {
        Vehicle vehicle = createVehicle();
        vehicle.drive();
    }
}

// Concrete Creators
class CarFactory extends VehicleFactory {
    public Vehicle createVehicle() {
        return new Car();
    }
}

class MotorcycleFactory extends VehicleFactory {
    public Vehicle createVehicle() {
        return new Motorcycle();
    }
}

// Client Code
public class FactoryMethodExample {
    public static void main(String[] args) {
        VehicleFactory carFactory = new CarFactory();
        carFactory.manufactureVehicle(); // Output: Driving a car.

        VehicleFactory motorcycleFactory = new MotorcycleFactory();
        motorcycleFactory.manufactureVehicle(); // Output: Riding a motorcycle.
    }
}

In this example, Vehicle is the Product interface, and Car and Motorcycle are the Concrete Products. VehicleFactory is the Creator class, and CarFactory and MotorcycleFactory are the Concrete Creators. The client code can create different types of vehicles by instantiating the appropriate factory class and calling the manufactureVehicle() method.

Conclusion

The Factory Method Pattern is a powerful technique for creating objects in a flexible and extensible manner. It promotes loose coupling, encapsulation of creation logic, and the ability to introduce new products or creators without modifying existing code. By understanding and applying this pattern, you can write more maintainable and scalable object-oriented software.

Avatar

Neelabh

About Author

As Neelabh Singh, I am a Senior Software Engineer with 6.6 years of experience, specializing in Java technologies, Microservices, AWS, Algorithms, and Data Structures. I am also a technology blogger and an active participant in several online coding communities.

You may also like

Blog Design Pattern

Understanding the Builder Design Pattern in Java | Creational Design Patterns | CodeTechSummit

Overview The Builder design pattern is a creational pattern used to construct a complex object step by step. It separates
Blog Tech Toolkit

Base64 Decode

Base64 encoding is a technique used to encode binary data into ASCII characters, making it easier to transmit data over