creational
Factory
A factory is a function that decides which object to build and how, so callers ask for what they need without importing concrete classes or repeating construction logic. In TypeScript it is usually a plain function that returns an interface. The Factory Method and Abstract Factory variants exist mainly to get the same effect in languages without first-class functions.
Use it for
- Choosing an implementation from configuration or environment: a real mailer in production, an in-memory one in tests.
- Construction that needs validation, defaults, or several collaborators wired together.
Watch for
- A factory with one product and no decision to make is a constructor with extra steps.
- A switch over a growing list of types inside the factory becomes the place every change collides. A registry — a record of builders keyed by type — keeps each addition local.
interface Mailer {
send(to: string, body: string): Promise<void>
}
export function createMailer(env: Env): Mailer {
if (env.NODE_ENV === "test") return memoryMailer()
return smtpMailer({ host: env.SMTP_HOST, apiKey: env.SMTP_KEY })
}