Creational PatternsAbstract Factory PatternEasy⏱️ ~2 min

What is the Abstract Factory Pattern?

Definition
Abstract Factory Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It encapsulates a group of individual factories that have a common theme.

The pattern solves the problem of creating objects that belong to the same product family while maintaining consistency across those objects. Instead of calling constructors directly, client code uses factory methods to create objects, which allows the system to work with any product family without being coupled to concrete classes.

Core Problem

When you need to create multiple related objects that must be used together (such as UI components for different operating systems), directly instantiating concrete classes leads to tight coupling. If you need to support a new product family, you must modify client code throughout the application.

Solution Approach

First, define abstract interfaces for each type of product in the family. Second, create an abstract factory interface with methods for creating each product type. Third, implement concrete factory classes for each product family. Finally, client code depends only on abstract interfaces, not concrete classes.

Interview Tip: Always explain that Abstract Factory creates "families" of objects, not just single objects. This distinguishes it from Factory Method.

When to Use

Use Abstract Factory when your system needs to work with multiple families of related products, when you want to enforce consistency among products from the same family, or when you want to provide a library of products while hiding their concrete implementations. However, if you only have a single product family or products that don't need to be used together, a simpler Factory Method pattern is more appropriate.

💡 Key Takeaways
Creates families of related objects without specifying concrete classes
Enforces consistency by ensuring products from the same family are used together
Client code depends on abstract interfaces, enabling easy swapping of product families
Requires defining both product interfaces and factory interfaces
More complex than Factory Method but provides better encapsulation for related objects
📌 Examples
1UI toolkit supporting multiple operating systems (Windows buttons with Windows text fields)
2Document converter creating readers and writers for different formats (PDF, Word, HTML)
3Database access layer with factories for different database vendors (MySQL, PostgreSQL, Oracle)
← Back to Abstract Factory Pattern Overview
What is the Abstract Factory Pattern? | Abstract Factory Pattern - System Overflow