C# Interview Question #152
What is the Factory Pattern?
Design Patterns & Production Architecture Senior Advanced
Quick Interview Answer
The Factory Pattern centralizes object creation and hides the decision about which concrete implementation should be instantiated.
Detailed Explanation
The Factory Pattern centralizes object creation and hides the decision about which concrete implementation should be instantiated.
It is useful when object creation depends on runtime input, configuration, environment, or business rules.
In applications using dependency injection, factories can work alongside the DI container when selection between multiple implementations must happen dynamically.
Code Example
public interface IPaymentProcessor
{
Task ProcessAsync(decimal amount);
}
public class PaymentProcessorFactory
{
public IPaymentProcessor Create(string type)
{
return type switch
{
"card" => new CardPaymentProcessor(),
"paypal" => new PayPalPaymentProcessor(),
_ => throw new NotSupportedException()
};
}
}