Home/Learn/Low Level Design/Factory Method Pattern

Factory Method Pattern

Beginner
Creational Patterns

Defines an interface for creating an object but lets subclasses decide which class to instantiate, decoupling object creation from usage.

Overview

The Factory Method pattern moves the "new" keyword out of client code and into a dedicated factory method. The creator class declares an abstract factory method returning a Product interface; concrete creator subclasses override it to return specific product instances. Clients code against the Product interface and never reference concrete classes. This follows the Open/Closed Principle — adding a new product type requires only a new subclass, not modifying existing code. Common in Java standard library: Calendar.getInstance(), NumberFormat.getInstance(), Connection factories in JDBC.

Classic Factory Method

Define a Product interface and multiple ConcreteProduct implementations. The Creator declares an abstract factoryMethod(); ConcreteCreators return specific products. The client calls creator.factoryMethod() without knowing the concrete type.

Java — Classic Factory Method (Notification)
// Product interface
public interface Notification {
    void send(String message);
}

// Concrete products
public class EmailNotification implements Notification {
    private final String email;
    public EmailNotification(String email) { this.email = email; }

    @Override
    public void send(String message) {
        System.out.println("Email to " + email + ": " + message);
    }
}

public class SmsNotification implements Notification {
    private final String phone;
    public SmsNotification(String phone) { this.phone = phone; }

    @Override
    public void send(String message) {
        System.out.println("SMS to " + phone + ": " + message);
    }
}

// Abstract Creator
public abstract class NotificationService {
    // Factory Method — subclasses decide what to create
    protected abstract Notification createNotification(String recipient);

    public void notify(String recipient, String message) {
        Notification n = createNotification(recipient); // calls factory method
        n.send(message);
    }
}

// Concrete Creators
public class EmailNotificationService extends NotificationService {
    @Override
    protected Notification createNotification(String recipient) {
        return new EmailNotification(recipient);
    }
}

public class SmsNotificationService extends NotificationService {
    @Override
    protected Notification createNotification(String recipient) {
        return new SmsNotification(recipient);
    }
}

// Client
NotificationService service = new EmailNotificationService();
service.notify("user@example.com", "Your order has shipped!");

Static Factory Method (Simplified)

A pragmatic alternative is a static factory method in one class that switches on a type discriminator. Less flexible for extension but sufficient for most cases. Joshua Bloch (Effective Java Item 1) recommends static factories over constructors for clarity and caching.

Java — Static Factory Method with enum switch
public interface Parser {
    Object parse(String input);
}

public class JsonParser implements Parser {
    @Override public Object parse(String input) {
        System.out.println("Parsing JSON: " + input);
        return new Object();
    }
}

public class XmlParser implements Parser {
    @Override public Object parse(String input) {
        System.out.println("Parsing XML: " + input);
        return new Object();
    }
}

// Static factory — type-safe enum switch (Java 14+)
public class ParserFactory {
    public enum Format { JSON, XML, CSV }

    public static Parser create(Format format) {
        return switch (format) {
            case JSON -> new JsonParser();
            case XML  -> new XmlParser();
            case CSV  -> new CsvParser();
        };
    }
}

// Client
Parser parser = ParserFactory.create(ParserFactory.Format.JSON);
parser.parse("{"key":"value"}");

Key Points to Remember

  • 1Factory Method decouples the client from concrete classes — client codes against an interface.
  • 2Adding a new product type requires only a new ConcreteCreator subclass (OCP).
  • 3Static factory methods (Effective Java Item 1) are a simpler alternative when subclassing is unnecessary.
  • 4Java standard library examples: Calendar.getInstance(), Collections.unmodifiableList(), Optional.of().
  • 5Factory Method uses inheritance; Abstract Factory uses composition — key distinction.

Interview Questions

Sign in to ask Aria
1

What is the difference between Factory Method and Abstract Factory patterns?

MediumAmazon
2

How does Factory Method follow the Open/Closed Principle?

MediumGoogle
3

Give a real example of Factory Method in the Java standard library.

EasyMicrosoft
4

When would you prefer a static factory method over a constructor?

EasyFlipkart

Ask Aria about Factory Method Pattern

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…