Factory Method Pattern

PUBLISHED: 2026-07-21
AUTHOR: MANUEL PRIETO
Design Patterns

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

Purpose and Use Case

The Factory Method pattern suggests replacing direct object construction calls (using the new operator) with calls to a special factory method. It is ideal when you don't know beforehand the exact types and dependencies of the objects your code should work with.

Key Benefits (SOLID):

  • Avoids tight coupling: Decouples the client code from concrete product classes.
  • Single Responsibility Principle (SRP): Centralizes object creation logic into specific creator classes.
  • Open/Closed Principle (OCP): You can introduce new product types into the application without breaking existing client code.

Pattern Structure

The conceptual architecture consists of four main elements:

  1. Product (Interface): Declares the interface common to all objects created by the creator and its subclasses.
  2. Concrete Products: Different implementations of the product interface.
  3. Creator (Abstract Class/Interface): Declares the factory method returning product objects.
  4. Concrete Creators: Override the base factory method to return instances of specific concrete products.
Cargando diagrama...

How It Works

  1. Interface Definition: Define a uniform interface for all products (e.g., Notification).
  2. Concrete Implementation: Implement concrete classes (e.g., EmailNotification, SMSNotification, PushNotification).
  3. Creator Hierarchy: Define an abstract creator with a createNotification() factory method.
  4. Subclass Delegation: Subclasses override the factory method to return specific instances based on business logic.

Real-World Implementation Examples

Practical Code Example

To see a real-world admin panel refactoring in React/TypeScript applying this pattern alongside SOLID and YAGNI, check out our practical example:

💡 View Practical Example: Factory Pattern Practical Example