0Pricing
Java Academy · Lesson

Factory Method Pattern

Define a factory method in a base class and let subclasses decide which product to create.

Factory Method Pattern is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Factory Method Intent

Factory Method defines an interface for creating an object but lets subclasses decide which class to instantiate. It decouples the creation logic from the client code.

The Problem Without Factory Method

Without a factory, client code is littered with new ConcreteClass() calls. Adding a new variant means changing every call site — a violation of Open/Closed Principle.

// Client knows too much:
Shape shape;
if (type.equals("circle")) shape = new Circle(r);
else if (type.equals("rect")) shape = new Rectangle(w, h);
// Every new shape requires editing this code.

The Creator Abstract Class

Define an abstract creator class with a createProduct() factory method. Subclasses override it to return specific product types.

public abstract class Dialog {
    public void render() {
        Button btn = createButton(); // factory method
        btn.onClick();
    }
    protected abstract Button createButton();
}

Concrete Creators

Each subclass overrides the factory method to return the appropriate product without changing the surrounding algorithm in the base class.

public class WindowsDialog extends Dialog {
    @Override
    protected Button createButton() { return new WindowsButton(); }
}
public class WebDialog extends Dialog {
    @Override
    protected Button createButton() { return new HtmlButton(); }
}

The Product Interface

All concrete products implement a common interface so the creator can work with them generically.

public interface Button {
    void onClick();
    void render();
}
public class WindowsButton implements Button {
    public void onClick() { System.out.println("Windows click"); }
    public void render() { System.out.println("Render Windows button"); }
}

Static Factory Methods vs Factory Method Pattern

A static factory method (e.g., LocalDate.of()) is a naming convention, not the GoF pattern. The GoF pattern uses inheritance; static factories use static methods on a single class.

// Static factory (NOT the GoF pattern)
LocalDate d = LocalDate.of(2024, 6, 15);
// GoF Factory Method uses a class hierarchy

Parameterized Factory Method

Pass a parameter to the factory method to choose among several products without requiring a subclass per product.

public class ShapeFactory {
    public static Shape create(String type, double... dims) {
        return switch (type) {
            case "circle"    -> new Circle(dims[0]);
            case "rectangle" -> new Rectangle(dims[0], dims[1]);
            default -> throw new IllegalArgumentException("Unknown: " + type);
        };
    }
}

Factory Method with Generics

Use generics to make the factory method type-safe and reusable across different product families.

public abstract class Repository<T, ID> {
    public abstract T findById(ID id);
    protected abstract T createEmpty(); // factory method
}

Registering Factories with a Map

A registry-based factory stores a map of type strings to Supplier lambdas, avoiding if-else chains and making registration dynamic.

Map<String, Supplier<Notification>> registry = new HashMap<>();
registry.put("email", EmailNotification::new);
registry.put("sms",   SmsNotification::new);
Notification n = registry.getOrDefault(type, DefaultNotification::new).get();

Factory Method vs Abstract Factory

Factory Method creates one product type via inheritance. Abstract Factory creates families of related products via composition. Use Factory Method when one product varies; Abstract Factory when a whole suite varies together.

Real-World Example: Logger Factory

SLF4J's LoggerFactory.getLogger(Class) is a static factory that returns the correct logger implementation (Logback, Log4j, JUL) without the caller knowing which.

Logger log = LoggerFactory.getLogger(MyService.class);
log.info("Service started");

Quick Check

What is the key characteristic of the Factory Method pattern?

Recap

Factory Method decouples object creation from the client by placing the instantiation decision in overridable subclass methods. Use it when a class can't anticipate which objects it needs to create.

Frequently asked questions

Is the “Factory Method Pattern” lesson free?

Yes — the full text of “Factory Method Pattern” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Factory Method Pattern”?

Define a factory method in a base class and let subclasses decide which product to create. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Factory Method Pattern” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Singleton: Thread-Safe Implementations
  2. Factory Method Pattern
  3. Abstract Factory for Product Families
  4. Builder Pattern with Fluent API
← Back to Java Academy