← Back to Home

Abstract Factory Pattern

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

What is it?

Abstract Factory lets you produce different types of related objects using a common interface, making it easy to switch families of components without breaking client code.

Example

interface Button {
  render(): string;
}

interface Checkbox {
  render(): string;
}

class LightButton implements Button {
  render() {
    return "Light Button";
  }
}

class DarkButton implements Button {
  render() {
    return "Dark Button";
  }
}

interface GUIFactory {
  createButton(): Button;
  createCheckbox(): Checkbox;
}

class LightThemeFactory implements GUIFactory {
  createButton() { return new LightButton(); }
  createCheckbox() { return new LightCheckbox(); }
}

Common Uses

  • UI toolkits (light/dark themes)
  • Cross-platform apps (Mac vs Windows components)
  • Dependency injection for family object creation

When to Use

  • You need to create multiple families of related objects
  • You want to switch entire sets of objects easily

Caution

  • Can grow complex with many products/factories
  • May lead to lots of boilerplate classes