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
- Select a product family
- Factory creates button and toggle
- 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
Editorial suitability, not benchmarks or a universal ranking. Styles describe different axes and can be combined.
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.
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.
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
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.
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.