Course contentsShow
← Computer Science
Lesson 2267 of 2,87251. Design PatternsFree lesson

Factory Method Pattern Basics

Defining an interface for object creation while letting subclasses decide which class to instantiate.

Factory Method Pattern Basics

What you'll learn: How to delegate object creation decisions to subclasses through a flexible, extensible interface.

The Core Problem

Imagine you're building a logistics app that manages truck delivery. Later, you want to add ship delivery. If you hard-code new Truck() everywhere, you'll need to change code in dozens of places. The Factory Method pattern solves this by centralizing creation logic.

How It Works

Instead of calling constructors directly, you define a factory method — an interface or abstract method that returns objects. Subclasses override this method to decide which concrete class to instantiate.

The key players:

  1. Creator (abstract) — declares the factory method
  2. Concrete Creators — implement the method, returning specific product types
  3. Product (interface) — common interface for all objects the factory creates
  4. Concrete Products — actual implementations

Plain-English Analogy

Think of a restaurant menu system. The Restaurant class has an abstract createDish() method. ItalianRestaurant overrides it to return Pizza, while JapaneseRestaurant returns Sushi. The client code just calls createDish() without knowing whether it gets pizza or sushi — the subclass decides.

Why Use It?

  • Decoupling: Client code doesn't depend on concrete classes
  • Extensibility: Add new product types without modifying existing code
  • Single Responsibility: Creation logic lives in one place per product family

You've already seen the Singleton pattern control how many instances exist. Factory Method controls which class gets instantiated.

Key Takeaway: Factory Method defines a creation interface but lets subclasses choose the concrete class, making your code flexible and extension-friendly.