Skip to content
Veltoryx Technologies
ProLesson 4.3Intermediate7 min readUpdated 31 October 2026

Abstract Factory Pattern

Learn how to create whole families of matching objects through one factory, using a light and dark theme example, and how it differs from Factory Method.

Imagine you walk into a furniture shop. The shop sells furniture in styles: Modern and Victorian. If you choose the Modern style, you get a modern sofa, a modern table and a modern chair, and they match each other. Nobody wants a Victorian sofa with a Modern table. The style is a family of things that belong together.

The Abstract Factory pattern is the code version of this shop. It gives you one factory per family, and each factory knows how to create all the matching pieces of its family. You pick a factory once, and everything you build from it fits together.

In the last lesson you learnt about Factory Method, which creates one kind of product. Abstract Factory is the next step: it creates several related products that must stay consistent.

01The problem: pieces that must match

An application has a settings screen with a button and a menu. The user can choose a light theme or a dark theme. A first version might decide the theme every time it creates a piece:

Theme decisions repeated for every piece
Button saveButton;
Menu topMenu;

if (theme.equals("DARK")) {
    saveButton = new DarkButton();
    topMenu = new DarkMenu();
} else {
    saveButton = new LightButton();
    topMenu = new LightMenu();
}

Now think about a real application with dozens of screens and a dozen kinds of controls: buttons, menus, checkboxes, dialogs, tabs. The theme check gets copied everywhere. Sooner or later someone writes:

The bug that nobody notices in review
Button saveButton = new DarkButton();
Menu topMenu = new LightMenu();      // oops: a mismatched pair

The screen now has a dark button on a light menu. The compiler cannot catch this, because both are valid. Besides, adding a third theme, "high contrast", means finding and editing every one of those checks.

We want a design where:

  1. the choice of theme is made once,
  2. every control comes from the same family, so mismatches become impossible,
  3. the screen code does not know which theme it uses.

Loading the rest of the lesson…