Abstract Factory

creational

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Intent

The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Motivation

When your code needs to work with various families of related products, but you don't want it to depend on the concrete classes of those products, Abstract Factory is useful. It's particularly helpful for ensuring that products from the same family are used together.

Structure

The pattern declares interfaces for creating each distinct product. Concrete factory classes implement these creation methods. Each concrete factory corresponds to a specific variant of products.

Participants

  • AbstractFactory - declares an interface for operations that create abstract product objects
  • ConcreteFactory - implements the operations to create concrete product objects
  • AbstractProduct - declares an interface for a type of product object
  • ConcreteProduct - defines a product object to be created by the corresponding concrete factory
  • Client - uses only interfaces declared by AbstractFactory and AbstractProduct classes

Pros

  • Isolates concrete classes
  • Makes exchanging product families easy
  • Promotes consistency among products
  • Follows Open/Closed Principle

Cons

  • Difficult to support new kinds of products
  • Increases complexity with many interfaces and classes

Use Cases

UI libraries with different themes
Cross-platform applications
Database connection factories
Document generators for different formats

Implementation Tips

Considerations

  • Factories are often implemented as Singletons
  • Creating products can use Factory Method or Prototype
  • Consider using dependency injection

Tips

  • Use dependency injection to provide the factory
  • Consider defining factories as singletons
  • Use descriptive names for concrete factories
  • Document which products belong to which family

Interactive Code Editor