Skip to main content

What is the Abstract Factory pattern?

Abstract Factory is a creational design pattern that lets you create families of related objects without specifying their concrete classes.


1. The core idea

If a system has several groups of related products (for example, an interface for Windows and for macOS), Abstract Factory provides a single interface through which you can create compatible objects for each group.

The client does not know which exact classes are created - it works only with abstractions.


2. When it is used

  • When you need to guarantee compatibility of the created objects (for example, a button, a window, and a menu must belong to the same platform).
  • When the system must be independent of the concrete classes it works with.
  • When you need to easily switch product families (for example, from a "light" theme to a "dark" one).

3. Structure

  1. AbstractFactory - declares the interface for creating objects of different types.
  2. ConcreteFactory - implements the interface and creates specific products.
  3. AbstractProductA/B - interfaces for individual products.
  4. ConcreteProductA/B - concrete implementations.
  5. Client - uses only the abstract interfaces, without knowing the concrete classes.

4. Example (Java)

java
// Abstract products interface Button { void paint(); } interface Checkbox { void paint(); } // Concrete products class WinButton implements Button { public void paint() { System.out.println("Windows Button"); } } class MacButton implements Button { public void paint() { System.out.println("Mac Button"); } } // Abstract factory interface GUIFactory { Button createButton(); Checkbox createCheckbox(); } // Concrete factories class WinFactory implements GUIFactory { public Button createButton() { return new WinButton(); } public Checkbox createCheckbox() { return new WinCheckbox(); } } class MacFactory implements GUIFactory { public Button createButton() { return new MacButton(); } public Checkbox createCheckbox() { return new MacCheckbox(); } }

5. Advantages

  • Guarantees compatibility of products within the same family.
  • Isolates the client code from concrete classes.
  • Makes it easier to add new product families.

6. Disadvantages

  • Adding a new product type requires changing the interface of all factories (violates OCP).
  • Increases the number of classes and abstractions.

Summary: Abstract Factory creates whole sets of related objects (not just one, like Factory Method), ensuring their consistency and easy switching between product families.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.