Factory Method
Defines an interface for creating objects, letting subclasses decide which class to instantiate.
Understanding Factory Method
The Factory Method pattern defines an interface for creating objects but delegates the decision of which concrete type to instantiate to a factory function or method. In Go, this is typically implemented as a constructor function (e.g. NewXxx()) that returns an interface type rather than a concrete struct. This decouples client code from specific implementations, making it easy to add new product types without modifying existing code — a key principle of the Open/Closed principle.
Key Concepts
- •Product interface — defines the contract that all created objects must satisfy, allowing the client to use any product interchangeably
- •Concrete products — different structs that implement the product interface, each with their own behavior
- •Factory function — a
New*()function that takes a discriminator (string, enum, config) and returns the correct implementation behind the interface - •Loose coupling — the client never imports or references concrete types directly, only the interface and the factory
When to Use
- • The exact type of object to create is determined at runtime
- • You want to centralize and encapsulate the creation logic
- • New product types are added frequently and independently
- • You're building a plugin or driver system
- • You only ever create one type — direct construction is simpler
- • The product types are trivial and unlikely to change
- • Adding a factory adds indirection without real benefit
Structure
How It Works
Client Request
Client asks the factory to create a product without knowing the concrete type.
Basic Implementation
A simple factory function that creates different document types:
Real-World Example: Logger Factory
A configurable logger factory that creates different logging backends: