Abstract Factory

Category

Creational pattern

Problem

Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Useful when you need to ensure that created objects are compatible with each other.

Solution

  • Define an abstract factory interface with methods for creating each type of product
  • Create concrete factory classes, each responsible for creating a specific family of products
  • Client code uses the factory interface, never instantiating concrete products directly
  • Swapping factories changes the entire family of products consistently

Structure

  • AbstractFactory: Declares operations for creating abstract product types
  • ConcreteFactory: Implements creation operations for a specific product family
  • AbstractProduct: Declares interfaces for a type of product object
  • ConcreteProduct: Implements the product interface; created by corresponding concrete factory
  • Client: Uses only interfaces declared by AbstractFactory and AbstractProduct

Key Benefits

  • Ensures product compatibility — All products from one factory work together
  • Swaps product families — Change the active factory to switch entire product families
  • Open/Closed Principle — New product families can be added without modifying client code

Trade-offs

  • Difficult to add new product types — Requires changes to the factory interface and all concrete factories
  • Adds complexity — More classes and abstractions than simpler patterns like Factory Method

When to Use

  • A system should be independent of how its products are created, composed, and represented
  • A system needs to be configured with one of multiple families of products
  • A family of related product objects is designed to be used together, and you need to enforce this constraint

Examples

  • Spring Framework use abstract factories to create themed widget families
  • Cross-platform GUI frameworks create platform-specific widgets through abstract factories

See Also