Factory Method: creating objects without coupling the decision to the flow
How Factory Method helps encapsulate object creation when the concrete type depends on context, channel or provider.
- #gof
- #factory-method
- #arquitectura
- #creacion-objetos
Executive summary
- Factory Method is useful when object creation has become an architecture decision.
- The flow gains stability because it stops knowing providers or concrete classes.
The real problem
Coupling often enters through an innocent line: new MercadoPagoClient(), new StripeClient(), new LocalNotifier(). Then more providers, channels and conditions appear around creation.
When the main flow decides which concrete class to instantiate, every provider change threatens logic that should not change.
What Factory Method solves
Factory Method encapsulates creation behind a method or function. The consumer receives an interface and does not need to know the concrete class.
The creation decision still exists, but it lives in an explicit and testable point.
How it looks in code
The payment flow depends on a contract. Provider selection stays outside.
type PaymentProvider = { charge(amount: number): Promise<void> };
function createPaymentProvider(country: string): PaymentProvider {
if (country === "AR") return new MercadoPagoProvider();
return new StripeProvider();
}
async function checkout(country: string, amount: number) {
const provider = createPaymentProvider(country);
await provider.charge(amount);
}When to use it
Factory Method is useful when creation depends on a decision that may change:
- The provider depends on country, tenant, channel or configuration.
- You want to test the flow with fake implementations.
- The concrete class requires specific setup or credentials.
- There are several products that satisfy the same contract.
When to avoid it
If you always create the same class and there is no variability, a factory only adds indirection. Use it when creation is an architecture decision, not a habit.
Related evidence
FAQ
- Is Factory Method the same as Abstract Factory?
- No. Factory Method creates one product behind a contract. Abstract Factory creates families of related products that must remain consistent.
- Is a factory function enough?
- Often yes. In TypeScript or JavaScript, a simple function can express Factory Method without creating an unnecessary class hierarchy.