Abstract Factory
Creates families of related objects without specifying their concrete classes.
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
- • 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
- • 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
How It Works
Select Factory
Client selects a concrete factory (e.g., Dark or Light theme).
Basic Implementation
A UI theme factory that creates matching buttons and checkboxes:
Real-World Example: Database Abstraction
Database factory that creates compatible connection and query objects: