Tutorials Design Patterns Mastery
Factory Method: Abstracting complex object creation
On this page
Factory Method Pattern
The Factory Method pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. It allows a class to defer instantiation to subclasses, keeping your high-level business logic completely decpule from "which specific object" is being used.
1. Why not just use "new"?
If you write var logger = new SQLServerLogger(); in 500 files, and next month the client wants AzureBlobLogger, you have to edit 500 files. A Factory solves this.
public abstract class LoggerFactory
{
// The Factory Method
public abstract ILogger CreateLogger();
}
public class CloudLoggerFactory : LoggerFactory
{
public override ILogger CreateLogger() => new AzureBlobLogger();
}
2. Real-World .NET Example: IHttpClientFactory
In ASP.NET Core, you never instantiate new HttpClient(). You use a Factory. Why? Because raw HttpClients leak sockets. The Factory manages the underlying pooling and lifecycle of "Handlers" automatically, ensuring your server doesn't crash under high load.
4. Interview Mastery
Q: "When is the Factory Method better than simple Dependency Injection?"
Architect Answer: "Standard DI is great for 'Static' dependencies that exist for the whole request. You use a Factory when you need **Dynamic** creation. For example, if you need to create a new 'ProcessingTask' object every time a user clicks a button, you can't inject that task into the constructor (because it doesn't exist yet). You inject a `ITaskFactory`, and call `.Create()` at the exact millisecond the user clicks."