Skip to main content

What It Is

The Abstract Factory pattern creates whole families of related objects that belong together. Where a factory method makes one product, an abstract factory makes a matching set — and guarantees the pieces are never mixed.

The classic case is theming: a light theme must produce light buttons and light labels, never a mix.


Example: A Theme Factory

renderScreen takes any UIFactory and builds a consistent screen from it. Swapping the whole look is one argument — and mixing themes is impossible by construction.

One factory, one consistent family

The light theme produces only light parts, the dark theme only dark ones. renderScreen never changes.

Prompt
Write a Go program with an abstract UI factory: Button and Label interfaces, a UIFactory interface with NewButton and NewLabel, and LightTheme and DarkTheme factories producing matching light or dark parts. A renderScreen function renders a screen with any factory; render one light and one dark screen.
Output: Go program and captured output

When to Use It

Use it when several objects must stay consistent with each other — themes, platform widget sets, matching import/export format pairs.

Skip it when the products do not need to match. Independent objects deserve independent constructors, not a family factory.


Pros and Cons

Pros: family consistency is guaranteed; whole families swap with one value; calling code depends only on interfaces.

Cons: a lot of interfaces and types for a small job; adding a new product to the family means touching every factory.