SOLID & Design Patterns Interview Question #53

What is the difference between Factory and Builder?

Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate

Quick Interview Answer

A factory normally returns a complete object in one creation operation and hides which concrete implementation is instantiated. A builder focuses on constructing a complex object incrementally through a sequence of configuration steps.

Detailed Explanation

A factory normally returns a complete object in one creation operation and hides which concrete implementation is instantiated. A builder focuses on constructing a complex object incrementally through a sequence of configuration steps.

Factories are useful for choosing among implementations, while builders are useful when one object's construction has many optional or ordered parts. They can also be combined when a factory chooses which builder to use.

Code Example

// Factory
var exporter = factory.Create("pdf");

// Builder
var report = new ReportBuilder()
    .WithTitle("Sales")
    .IncludeCharts()
    .Build();