Course contentsShow
← Software Engineering
Lesson 234 of 1,9337. Creational Design PatternsFree lesson

Factory Method Pattern: Intent and Structure

Define an interface for creating objects, letting subclasses decide which class to instantiate.

Factory Method Pattern: Intent and Structure

What you'll learn: How the Factory Method pattern defines an interface for creating objects while letting subclasses decide which specific class to instantiate.

The Core Problem

Imagine you're building a document editor that can create different types of documents—text documents, spreadsheets, presentations. If you hardcode new TextDocument() directly in your application code, adding a new document type means modifying existing code, violating the Open/Closed Principle you've learned.

What is the Factory Method Pattern?

The Factory Method pattern solves this by defining an interface or abstract method for creating objects, but delegates the actual instantiation decision to subclasses. Instead of calling constructors directly, you call a method (the "factory method"), and subclasses override that method to specify which concrete class to create.

Structure

The pattern involves:

  • Creator (abstract or interface): declares the factory method that returns an object
  • Concrete Creators: subclasses that override the factory method to instantiate specific classes
  • Product (interface): defines what objects the factory method creates
  • Concrete Products: the actual classes being instantiated

A Simple Analogy

Think of a restaurant chain. The corporate headquarters defines a method createDailySpecial(), but each franchise location decides what specific dish that method produces. The headquarters doesn't need to know whether it's pizza, tacos, or salad—it just calls the method and gets some daily special that follows the company's food standards.

Why This Matters

This pattern inverts the dependency: your high-level application code depends on abstractions (the Creator and Product interfaces), not concrete classes. This aligns perfectly with the Dependency Inversion Principle you've studied.

Key Takeaway: Factory Method defines what to create through an interface, while letting subclasses decide which concrete class to instantiate, supporting extensibility without modification.