Skip to main content

Abstract Factory Pattern

Create families of related objects without specifying concrete classes

Pattern Overview

🏗️ Abstract Factory Pattern

The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It ensures that objects created together are compatible.

Core Concepts

🔹 Abstract Factory - Interface for creating families of related objects
🔹 Concrete Factory - Implements abstract factory for specific product families
🔹 Abstract Product - Interface for a type of product object
🔹 Concrete Product - Specific implementation of abstract product

Real-World Applications

UI Themes - Create matching buttons, inputs, modals for light/dark themes Database Drivers - Create compatible connection, query, transaction objects Cross-Platform Development - Create platform-specific UI components Game Engines - Create renderer-specific graphics, audio, input objects

Implementation Benefits

Consistency - Ensures related objects work together
Flexibility - Easy to switch entire product families
Isolation - Client code doesn't depend on concrete classes
Extensibility - New product families can be added easily

Examples:
Create UI components that match the selected theme automatically
Input:
createDarkThemeApp().createUserInterface()
Output:
UI Components with dark theme styling
Create database components that work with specific database engines
Input:
new PostgreSQLFactory().createConnection()
Output:
PostgreSQL-compatible database components
Configure entire application with compatible UI and database factories
Input:
createLightThemeApp() with database setup
Output:
Fully configured application with light theme UI and PostgreSQL database

Concepts

abstract interfacesobject familiescreational patternloose coupling

Complexity Analysis

Time:O(1)
Space:O(1)

Implementation

ui-theme-factory

Time: O(1) | Space: O(1)
// UI Factory implementation for different themes
class LightUIFactory implements UIFactory {
  createButton(text: string): Button {
    return new LightButton(text);
  }

  createInput(placeholder: string): Input {
    return new LightInput(placeholder);
  }

  createModal(title: string, content: string): Modal {
    return new LightModal(title, content);
  }
}

class DarkUIFactory implements UIFactory {
  createButton(text: string): Button {
    return new DarkButton(text);
  }

  createInput(placeholder: string): Input {
    return new DarkInput(placeholder);
  }

  createModal(title: string, content: string): Modal {
    return new DarkModal(title, content);
  }
}