← All topics
🧩 Design Patterns

Factory Pattern

Encapsulating object creation logic, especially 'which implementation' decisions.

A Factory centralizes the logic for which concrete type to instantiate, so callers depend only on the abstraction. Two flavors worth distinguishing in an interview:

In modern .NET, a lot of what Factory used to do by hand is now covered by the DI container itself (Func injection, or .NET 8 keyed services — see below) — knowing when the container already solves it, versus when you need an explicit factory class, is the senior-level distinction.

Flashcards (2)

What's the difference between Factory Method and Abstract Factory?
tap to reveal answer
Factory Method: one creation method returning one product type based on input. Abstract Factory: an interface with several creation methods producing a whole family of related objects that need to stay consistent with each other (e.g. matching UI components for a theme).
In modern .NET, what two container features can replace a hand-rolled factory class?
tap to reveal answer
Injecting Func<T> (or Func<string, T>) to defer/parametrize creation, or .NET 8 Keyed DI Services (AddKeyedSingleton + [FromKeyedServices]) when the 'which implementation' decision is a fixed set of keys known at registration time.