Factory Method
Intent
Let a parent define the steps of making something while children decide which exact kind to produce.
Motivation
A notifier sends alerts, but the channel varies: email needs an SMTP client, SMS needs a carrier gateway. If the alert code news up concrete senders, every new channel edits it. Factory Method keeps the alert flow fixed and pushes the “which sender” choice into small creator units — one per channel.
Structure
flowchart LR App[Alert App] --> Creator[Notifier Creator] Creator --> EmailCreator[Email Notifier Creator] Creator --> SmsCreator[SMS Notifier Creator] EmailCreator --> EmailSender[Email Sender] SmsCreator --> SmsSender[SMS Sender]
- Creator — declares the factory step and owns the alert flow.
- Concrete creators — Email/SMS creators that return their sender.
- Products — EmailSender, SmsSender with a shared send step.
Consequences
- Benefit: adding a channel adds a creator, never edits the alert flow.
- Cost: one creator type per product; simple one-off creation becomes heavier.
Basic Recap
Factory Method lets a creator defer construction of one collaborator to an overridable step. The creator keeps the surrounding workflow stable, while a subclass or supplied implementation chooses the concrete product. Callers use the product through a common interface rather than learning each constructor. The pattern separates a recurring process from the decision about which object that process needs.
Complex Scenario
A multi-tenant ingestion service validates and imports uploaded records with the
same job workflow, but each tenant supplies a different storage connector. An
ImportJob creator opens the upload, obtains a connector through
createConnector, normalizes records, and commits the batch. Connector creation
includes tenant credentials and endpoint selection, yet those details must not
leak into validation or batch accounting. The useful boundary is therefore one
connector per job, not an unconstrained object factory for every record.
Edge cases
- Concurrency: Two jobs for one tenant may create connectors simultaneously; connection-pool initialization must be safe, and job-specific cursors must not be shared between products.
- Retries: A retry after commit ambiguity must reuse the import idempotency key, while a fresh connector attempt must not reset the job’s source offset.
- Partial failure: If connector creation fails after credentials are opened, the creator must close temporary resources before reporting a retryable error.
Keep product selection separate from execution policy so the workflow can decide whether creation failure is retryable without understanding a vendor API.
Sketch (illustrative pseudocode, not runnable):
ImportJob.run(upload):
connector = this.createConnector(upload.tenant)
try:
validated = validate(upload.records)
result = connector.writeBatch(validated, upload.importKey)
return reconcile(result, upload.importKey)
finally:
connector.close()
TenantAJob.createConnector(tenant):
return ConnectorA(tenant.credentials, perJobPool())
TenantBJob.createConnector(tenant):
return ConnectorB(tenant.endpoint, tenant.credentials)
When to Use / When Not to Use
Use when:
- One flow works with several product kinds chosen at runtime or config time.
Avoid when:
- The product kind never varies or construction is a single
newwith no flow around it.
Examples
examples/elixir/factory-method/examples/dart/factory-method/examples/go/factory-method/examples/rust/factory-method/
Expected outcome: sending via email then SMS prints two lines naming each channel.
Anti-pattern / Failure Mode
-
Misuse: Hiding every
newbehind a creator hierarchy even when construction has no surrounding flow. -
Review signal: Constructors with no common product interface, or a factory chosen by a long type-switch.
-
Misuse symptom: Every simple
newis hidden behind a creator hierarchy, and adding a connector requires edits to job logic as well as a new subclass. The factory then adds indirection without protecting a stable workflow. -
Review signal: Look for constructors with no meaningful common product interface, factory methods selected by long type-switch statements, or tests that must instantiate the entire job hierarchy just to obtain one connector. Creation metrics that spike per record instead of per job also reveal a boundary drawn at the wrong granularity.
Related
- Abstract Factory — one product kind per creator vs a matching family.
- Builder — choose Builder when assembly needs ordered steps plus validation.
- Open/Closed — extend by adding creators, not editing the flow.
Exercise
Add a push-notification creator without touching the alert flow. Show the two-line output.
Self-check
- Who decides the concrete kind?
Answer
The concrete creator — the app asks the creator, never news the product directly. - Factory Method vs Abstract Factory?
Answer
Factory Method makes one product kind per creator; Abstract Factory makes families of related products.