Skip to content

Design Patterns

Abstract Factory

Building one full set takes O(k) time, where k is the number of pieces in the family (a fixed count, just like n but for a different total). The win here is consistency, not speed.

The idea, in plain English

An abstract factory is a factory that makes matching SETS of things, not just one thing. Think of a furniture showroom. Pick the 'modern' style and you get a matching modern chair AND a matching modern sofa. Pick 'classic' and you get a classic chair and classic sofa instead. You never mix a modern chair with a classic sofa by accident, because one factory hands you the whole matching set.

How it works

  1. 1You define one factory 'family' per matching set — like a Light theme factory and a Dark theme factory.
  2. 2Each factory knows how to build every piece in its set (button, checkbox, and so on), so they all match.
  3. 3Your code just asks the chosen factory for each piece. It never has to check styles or mix pieces from different families by hand.

When you'd use it

Use this when you need groups of related objects that must match each other. Examples: UI themes (light/dark), furniture styles, or cross-platform widgets (Windows-style vs Mac-style buttons and menus).

Common beginner mistakes

  • Don't mix pieces from two different factories. That defeats the whole point of keeping a set matching.
  • When you add a new piece to the family, implement it in every factory, or one theme stays incomplete.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Light theme: Light Button, Light Checkbox
Dark theme: Dark Button, Dark Checkbox

Not sure this is the right topic? See the learning paths → or where this leads →