Patterns: creation · 3 MIN READ

Abstract Factory: compatible product families

Create related products through one selected family.

Create related products through one selected family. Abstract Factory selects a family of products that should work together. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.

Creational pattern · A MAP OF THE IDEA

  1. Select a product family
  2. Factory creates button and toggle
  3. Client uses compatible products

Useful when

  • Related product roles must vary together
  • Mixing integrations would be invalid

Watch out

  • New product roles affect all factories
  • A configuration struct is often enough

Implementation & operation cost: Medium

Fit depends on the task

Small tool or CLI2/5
Domain-rich application3/5
Independent distributed services3/5

Editorial suitability, not benchmarks or a universal ranking. Styles describe different axes and can be combined.

01

The design decision

Abstract Factory selects a family of products that should work together. A UI theme might create both buttons and toggles; a storage integration might create matching readers and writers. Returning one object with many options is configuration, not necessarily a product family.

02

A complete Go example

Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.

go
package main

import (
	"fmt"
)

type Button struct{ theme string }
type Toggle struct{ theme string }
type Factory interface {
	Button() Button
	Toggle() Toggle
}
type Dark struct{}

func (Dark) Button() Button   { return Button{theme: "dark"} }
func (Dark) Toggle() Toggle   { return Toggle{theme: "dark"} }
func Screen(f Factory) string { return f.Button().theme + "/" + f.Toggle().theme }

func main() {
	fmt.Println(Screen(Dark{}))
}

// Output:
// dark/dark
Read the code

Screen requests two distinct product roles from the same factory, keeping the family consistent. Dark can be replaced with another factory implementing both methods. In a real package, keep constructors controlled if mixed families would violate invariants.

03

Tradeoffs and the simpler alternative

This helps when families vary together and incompatible combinations cause bugs. Adding a new product role changes every factory, so a config struct or a single constructor is often cheaper for a small stable set of values.

TAKE THIS WITH YOU

Creates compatible products from one selected family. This helps when families vary together and incompatible combinations cause bugs. Adding a new product role changes every factory, so a config struct or a single constructor is often cheaper for a small stable set of values.

Check your understanding

Which statement best describes Abstract Factory: compatible product families?

Go to the source

Progress stays in this browser. No account needed.