Use a factory to choose the type of object. Use a builder to put together one complex object step by step. Both separate object creation from the code that uses the object.
A factory decides which concrete type to create. In the GoF (Gang of Four) Factory Method pattern, a subclass decides which class to create. In everyday TypeScript, a factory is often a function like createPaymentProvider(config). It returns a StripeProvider or a PaypalProvider behind a PaymentProvider interface. The caller gets a ready object in one call and does not know the concrete class.
A builder constructs one complex object step by step. It usually has a fluent API, where each method returns the builder so you can chain calls. It produces the object at the end with build(). It suits objects with many optional parts:
- a SQL query builder
- an HTTP request
- test data like
aUser().withRole("admin").build()
A builder avoids telescoping constructors: constructors with a long list of optional parameters. It can also validate the whole object before returning it.
In short: choose a factory to vary the type, and a builder to vary the construction.
- A factory chooses which concrete class to create and hides it behind an interface.
- A builder puts together one complex object step by step and ends with build().
- A builder fits objects with many optional parameters, query builders and test data.
- A factory varies the type. A builder varies the construction process.