Abstract Factory

Creates families of related objects without specifying their concrete classes.

Context

Your app needs to render UI that changes based on the system (Windows/macOS/Web). Each family (button, window, scrollbar) must be consistent: don't mix a macOS button with a Windows scrollbar.

Problem
  • Maintain consistency among related objects.
  • Allow changing entire families without affecting the client.
Solution

An interface (IUIFactory) declares methods to create each family member. Each concrete factory (MacFactory, WinFactory) ensures that all objects belong to the same set.

#Example in C#

public interface IButton   { void Render(); }
public interface ICheckbox { void Render(); }

public interface IUIFactory
{
    IButton CreateButton();
    ICheckbox CreateCheckbox();
}

public class MacFactory : IUIFactory
{
    public IButton CreateButton()     => new MacButton();
    public ICheckbox CreateCheckbox() => new MacCheckbox();
}

public class WinFactory : IUIFactory
{
    public IButton CreateButton()     => new WinButton();
    public ICheckbox CreateCheckbox() => new WinCheckbox();
}

public class App
{
    private readonly IUIFactory _ui;
    public App(IUIFactory ui) => _ui = ui;

    public void Render()
    {
        _ui.CreateButton().Render();
        _ui.CreateCheckbox().Render();
    }
}
When NOT to use it
  • When there's only one family and no others are anticipated.
  • When families don't share structure (then each product will evolve in a different direction).
Tradeoffs
Pro Con
Ensures consistency among products Adding a new product to the family breaks ALL factories
Client decoupled from concrete classes Extra indirection

#creational #gof #family