Creational

Abstract Factory

Creates families of related objects without specifying their concrete classes.

Cross-platform UIDatabase driversTheme systems

Understanding Abstract Factory

The Abstract Factory pattern provides an interface for creating families of related objects without specifying their concrete classes. Unlike the simple Factory Method that creates one product type, Abstract Factory creates multiple related products that are designed to work together — for example, a UI theme factory that produces matching buttons, checkboxes, and inputs all styled for the same theme. In Go, the abstract factory is an interface with multiple creation methods, and each concrete factory implements the full set.

Key Concepts

  • Product families — each factory creates a complete set of related objects (e.g., Button + Checkbox + Input) that are guaranteed to be compatible
  • Factory interface — defines creation methods for each product type; concrete factories implement all of them
  • Consistency guarantee — since one factory creates all products, you can't accidentally mix a dark button with a light checkbox
  • Swappable families — switching from one product family to another requires only changing the factory, not any client code

When to Use

✅ Use when
  • • You need to create families of related objects that must work together
  • • Your application supports multiple product variants (themes, DB engines, OS APIs)
  • • You want to enforce that all products come from the same family
  • • New families may be added in the future without modifying clients
⚠️ Avoid when
  • • You only create a single product type — use Factory Method instead
  • • Product families don't need to be consistent with each other
  • • The number of product types changes often, making the interface unstable

Structure

Client
↓ uses
<<AbstractFactory>> CreateA() + CreateB()
implements
FactoryDark
Dark A
Dark B
FactoryLight
Light A
Light B

How It Works

DarkFactory
LightFactory
UIFactory
CreateButton()
CreateCheckbox()
🖤 DarkButton
☑️ DarkCheckbox
1

Select Factory

Client selects a concrete factory (e.g., Dark or Light theme).

1 / 4

Basic Implementation

A UI theme factory that creates matching buttons and checkboxes:

main.go
Loading editor...

Real-World Example: Database Abstraction

Database factory that creates compatible connection and query objects:

main.go
Loading editor...