Factory Method

Create objects without specifying exact class

Overview

The Factory Method pattern defines an interface for creating objects, but lets subclasses decide which class to instantiate. It delegates the instantiation logic to subclasses.

This pattern is useful when you don't know ahead of time which exact types and dependencies your code will need to work with.

Key Concepts

Defines interface for object creation

Subclasses decide which class to instantiate

Promotes loose coupling

Follows Open/Closed Principle

Creator and product hierarchies

Code Example

java
1// Product interface
2interface Vehicle {
3    void drive();
4}
5
6// Concrete products
7class Car implements Vehicle {
8    @Override
9    public void drive() {
10        System.out.println("Driving a car on road");
11    }
12}
13
14class Bike implements Vehicle {
15    @Override
16    public void drive() {
17        System.out.println("Riding a bike on road");
18    }
19}
20
21class Truck implements Vehicle {
22    @Override
23    public void drive() {
24        System.out.println("Driving a heavy truck");
25    }
26}
27
28// Creator (Factory)
29abstract class VehicleFactory {
30    // Factory method - to be implemented by subclasses
31    public abstract Vehicle createVehicle();
32    
33    // Template method using factory method
34    public void deliverVehicle() {
35        Vehicle vehicle = createVehicle();
36        System.out.println("Delivering vehicle...");
37        vehicle.drive();
38    }
39}
40
41// Concrete factories
42class CarFactory extends VehicleFactory {
43    @Override
44    public Vehicle createVehicle() {
45        return new Car();
46    }
47}
48
49class BikeFactory extends VehicleFactory {
50    @Override
51    public Vehicle createVehicle() {
52        return new Bike();
53    }
54}
55
56class TruckFactory extends VehicleFactory {
57    @Override
58    public Vehicle createVehicle() {
59        return new Truck();
60    }
61}
62
63// Usage
64public class Main {
65    public static void main(String[] args) {
66        VehicleFactory factory;
67        
68        // Create car
69        factory = new CarFactory();
70        factory.deliverVehicle();
71        
72        // Create bike
73        factory = new BikeFactory();
74        factory.deliverVehicle();
75        
76        // Easy to add new vehicle types without changing existing code
77    }
78}

Each factory subclass creates a specific type of vehicle. Adding a new vehicle type requires only a new product class and factory, without modifying existing code.

When to Use

  • When you don't know the exact types of objects needed

  • When you want to delegate object creation to subclasses

  • When you want to provide a library of products

  • When you need to follow the Open/Closed Principle

Advantages

  • Loose coupling between creator and product

  • Follows Single Responsibility Principle

  • Follows Open/Closed Principle - easy to extend

  • More flexible than simple constructors

Disadvantages

  • Code can become more complicated with many subclasses

  • Requires creating a new subclass for each product type

Real-World Example

  • Restaurant: Different chefs (factories) prepare different cuisines (products)
  • Document Editor: Different document formats (PDF, Word, HTML) created by specific creators
  • UI Frameworks: Different button factories for Windows, Mac, Linux

Best Practices

  • 1.

    Use when you need flexibility in object creation

  • 2.

    Keep the factory method focused on creation logic only

  • 3.

    Consider using Simple Factory if you don't need subclass flexibility

  • 4.

    Combine with other patterns like Prototype or Builder when needed

💡 Interview Tips

  • Explain the difference from Simple Factory and Abstract Factory

  • Discuss how it follows OCP

  • Draw the class diagram showing creator and product hierarchies

  • Give real-world examples from frameworks (Spring, Collections)

  • Mention it's creational pattern focused on single product creation

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In
Factory Method - Creational Patterns | LLD | Revise Algo