🧩 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:
- Simple Factory / Factory Method: one method that takes some input and returns the right
- implementation — this is literally the missing piece in the email's
DiscountServicerefactor - (see Strategy Pattern).
- Abstract Factory: a factory interface with multiple creation methods, used when you need to
- create families of related objects consistently (e.g. a UI toolkit's
IWidgetFactoryproducing a - matching
IButton+ICheckboxfor a given theme).
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
In modern .NET, what two container features can replace a hand-rolled factory class?
tap to reveal answer