Introduction to Abstract Factory Pattern
Abstract Factory provides an interface for creating families of related objects without specifying their concrete classes.
The Problem
When you need to create related objects that must be used together:
typescript1// Without Abstract Factory - inconsistent families2function createAddressComponents(country: string) {3 let formatter, validator, parser;45 if (country === 'US') {6 formatter = new USAddressFormatter();7 validator = new UKAddressValidator(); // Bug! Wrong validator8 parser = new USAddressParser();9 }10 // Easy to mix incompatible components11}
The Solution: Abstract Factory
Ensure consistency by grouping related object creation:
typescript1// Abstract Factory2interface AddressFactory {3 createFormatter(): AddressFormatter;4 createValidator(): AddressValidator;5 createParser(): AddressParser;6}78// Concrete Factory - all components are compatible9class USAddressFactory implements AddressFactory {10 createFormatter() { return new USAddressFormatter(); }11 createValidator() { return new USAddressValidator(); }12 createParser() { return new USAddressParser(); }13}1415class UKAddressFactory implements AddressFactory {16 createFormatter() { return new UKAddressFormatter(); }17 createValidator() { return new UKAddressValidator(); }18 createParser() { return new UKAddressParser(); }19}
Pattern Structure
1┌─────────────────────────────┐2│ AddressFactory │3│ (Abstract Factory) │4│ ─────────────────────────── │5│ + createFormatter() │6│ + createValidator() │7│ + createParser() │8└─────────────┬───────────────┘9 │10 ┌─────────┴─────────┐11 ▼ ▼12┌───────────────┐ ┌───────────────┐13│USAddressFactory│ │UKAddressFactory│14│───────────────│ │───────────────│15│+ createFormatter│ │+ createFormatter│16│+ createValidator│ │+ createValidator│17│+ createParser() │ │+ createParser() │18└───────┬───────┘ └───────┬───────┘19 │ │20 ▼ ▼21 US Products UK Products22 (Formatter, (Formatter,23 Validator, Validator,24 Parser) Parser)
Abstract Factory vs Factory Method
| Aspect | Factory Method | Abstract Factory |
|---|---|---|
| Creates | One product | Family of products |
| Via | Inheritance | Object composition |
| Focus | Defer to subclass | Ensure compatibility |
| Complexity | Lower | Higher |
When to Use
- Product families - Objects must be used together
- Platform independence - Different implementations per platform
- Consistency - Prevent mixing incompatible components
- Configuration - Switch entire families at runtime
Benefits
- Ensures product compatibility within families
- Isolates concrete classes from client code
- Easy to exchange product families
- Promotes consistency across products
Summary
Abstract Factory is ideal when you need to create groups of related objects that must work together. It prevents mixing incompatible components and makes it easy to swap entire families.