Skip to main content
Design Patterns 80 XP · 8 min

Factory Method: The Virtual Constructor

Delegate object creation to subclasses — decouple the client from the concrete classes it instantiates.

Showing
Ad (728×90)

Why this matters

When you scatter new CSVParser() and new JSONParser() across your codebase, you bind the client tightly to concrete class names. Every time a new format arrives, you hunt down every if type == "csv" block. The Factory Method pattern defines an interface for creation but lets subclasses — or a factory function — decide which concrete class to instantiate. Adding a new type touches zero existing code.

The problem

Bad

The solution

Good

When to use it — and when not to

Use Factory Method when a class cannot anticipate the type of objects it needs to create, or when you want subclasses to control creation. Avoid it when you only ever have one concrete implementation — it adds indirection for no gain.

Key takeaway

Replace scattered if type == X: create X blocks with a single factory — adding new types then requires writing new code, never modifying old code.

Done with this lesson?

Mark it complete to earn XP and track your progress.