Skip to main content

Factory Method: Decoupling Object Creation from Business Logic

Design Patterns Explained: From Theory to Practice: Article 2

Updated 12 min readMarkdown
Part of seriesDesign Patterns

In the previous article, we explored the SOLID principles and how they help us build maintainable software. One of the ideas we discussed was the Open/Closed Principle: software should be open for extension but closed for modification.

Let's consider how that principle applies to a practical problem.

Imagine we're building a ticket management application. When a ticket is assigned to an employee, the system must notify them. Initially, we only support email notifications:

public class TicketService
{
    public void AssignTicket(Ticket ticket)
    {
        // Assign the ticket...

        var sender = new EmailNotificationSender();
        sender.Send($"Ticket assigned: {ticket.Title}");
    }
}

This works, but what happens when the business asks us to support SMS notifications as well?

We might introduce a conditional:

if (notificationType == "email")
{
    var sender = new EmailNotificationSender();
    sender.Send(message);
}
else if (notificationType == "sms")
{
    var sender = new SmsNotificationSender();
    sender.Send(message);
}

As more notification channels are introduced, this conditional grows. The class responsible for ticket assignment now needs to understand the different notification implementations and how to construct them.

This creates unnecessary coupling between business logic and object creation. Every new notification type potentially requires modifying existing code.

The Factory Method pattern provides one way to address this problem.

What is the Factory Method pattern?

The Factory Method is a creational design pattern that defines a method for creating objects but allows subclasses to decide which concrete class to instantiate.

Instead of directly constructing a concrete object, the creator delegates that decision to a method that subclasses can override.

The important distinction is that the creator does not simply exist to manufacture objects. It usually contains business logic that depends on the product abstraction. The factory method allows that business logic to work with different concrete implementations without being coupled to them.

For this reason, Factory Method is sometimes described as a virtual constructor: it provides an overridable method that determines which product implementation is returned.

In our ticket management application, the goal is to allow the notification workflow to work with different notification channels without depending directly on EmailNotificationSender or SmsNotificationSender.

Understanding the structure

The classic Factory Method pattern has four main participants:

Participant Ticket management example Responsibility
Product INotificationSender Defines the interface shared by all notification senders
Concrete Product EmailNotificationSender, SmsNotificationSender Implements a specific notification channel
Creator TicketNotificationCreator Declares the factory method and contains the workflow that uses the product
Concrete Creator EmailNotificationCreator, SmsNotificationCreator Overrides the factory method to select a concrete notification sender

There are two related class hierarchies here.

The product hierarchy represents the objects being created. In our example, email and SMS senders implement INotificationSender.

The creator hierarchy represents the classes responsible for deciding which product to provide. EmailNotificationCreator and SmsNotificationCreator inherit from TicketNotificationCreator.

This separation is what makes the pattern useful: subclasses can change the concrete product without changing the creator's underlying workflow.

However, it also introduces complexity. Each new product may require another concrete creator, meaning developers must maintain two related hierarchies. In everyday .NET applications, this can be excessive when a dependency injection container or a simple factory delegate could handle object creation more directly.

Let's see how the pattern works in practice.

Implementing Factory Method in C#

We'll build the example in small steps, starting with the product abstraction.

1. Define the product interface

First, we define the common interface that all notification senders must implement.

public interface INotificationSender
{
    void Send(string message);
}

The interface defines what a notification sender can do without specifying how the notification is delivered.

This allows the rest of the application to work with INotificationSender rather than depending on a particular notification channel.

2. Create the concrete products

Next, we implement the interface for each supported notification channel.

public class EmailNotificationSender : INotificationSender
{
    public void Send(string message)
    {
        Console.WriteLine($"Sending email: {message}");
    }
}

public class SmsNotificationSender : INotificationSender
{
    public void Send(string message)
    {
        Console.WriteLine($"Sending SMS: {message}");
    }
}

These classes represent the concrete products.

In a real application, they might integrate with an email provider or an SMS gateway. For this example, we'll keep the implementations simple and focus on the design.

Notice that both classes implement the same interface. This is important because the creator must be able to work with either implementation through a common abstraction.

3. Create the creator class

Now we introduce the central participant: the creator.

public abstract class TicketNotificationCreator
{
    protected abstract INotificationSender
        CreateNotificationSender();

    public void NotifyTicketAssigned(Ticket ticket)
    {
        var sender = CreateNotificationSender();

        sender.Send($"Ticket assigned: {ticket.Title}");
    }
}

There are two important parts to this class.

First, CreateNotificationSender() is the factory method. It returns an INotificationSender, but the creator does not specify which concrete implementation it will receive.

Second, NotifyTicketAssigned() contains the business workflow. It obtains a notification sender through the factory method and uses it to send the notification.

The creator depends on the product abstraction, not on a concrete notification class.

This is the central idea behind Factory Method: the creator's business logic remains independent of the concrete product being created.

4. Create the concrete creators

We now create subclasses that override the factory method and decide which notification sender to provide.

public class EmailNotificationCreator
    : TicketNotificationCreator
{
    protected override INotificationSender
        CreateNotificationSender()
    {
        return new EmailNotificationSender();
    }
}

public class SmsNotificationCreator
    : TicketNotificationCreator
{
    protected override INotificationSender
        CreateNotificationSender()
    {
        return new SmsNotificationSender();
    }
}

Each concrete creator provides a different implementation of the factory method.

The email creator returns an EmailNotificationSender, while the SMS creator returns an SmsNotificationSender.

The important point is that both return the same abstraction: INotificationSender.

The base creator therefore does not need to know which concrete sender it receives.

5. Use the pattern

Finally, the application chooses the appropriate creator and uses it.

TicketNotificationCreator creator =
    new EmailNotificationCreator();

creator.NotifyTicketAssigned(ticket);

To use SMS instead, we can provide a different creator:

TicketNotificationCreator creator =
    new SmsNotificationCreator();

creator.NotifyTicketAssigned(ticket);

The notification workflow remains unchanged. Only the concrete creator changes.

In a production application, the choice of creator would normally happen during application configuration or dependency composition, rather than being hard-coded into the ticket assignment operation.

The example is deliberately simplified: the concrete creators instantiate their senders directly. If those senders require additional dependencies, their construction would also need to account for those dependencies.

When should you use Factory Method?

Factory Method is useful when object creation needs to vary while the workflow using those objects remains consistent.

Consider using it in the following situations:

1. When subclasses need to customise object creation

A base class provides a workflow, but different subclasses need different implementations of one of the objects used by that workflow.

For example, a document-processing framework might define a common processing workflow while allowing subclasses to provide different document readers.

2. When you are building an extensible framework or library

Factory Method can give consumers of a framework a controlled way to customise internal components.

Instead of requiring users to modify the framework's existing code, you expose a factory method that can be overridden.

3. When object creation and business logic should evolve independently

If a class contains substantial business logic and also directly constructs several concrete dependencies, separating the creation decision can reduce coupling.

However, the pattern is not automatically the best solution whenever a class contains a new expression. The additional abstraction should solve a genuine design problem.

Advantages and disadvantages

Like any design pattern, Factory Method introduces trade-offs.

Advantages

  • Reduced coupling: The creator works with a product abstraction rather than depending directly on concrete implementations.
  • Extensibility: New product types can be introduced through additional concrete creators without changing the existing creator workflow.
  • Separation of responsibilities: The decision about which concrete product to provide is separated from the business logic that uses it.
  • Supports the Open/Closed Principle: Existing creator logic can remain unchanged when new concrete products are introduced.

Disadvantages

  • More classes: Each new product type may require another concrete creator, increasing the number of classes in the application.
  • Parallel hierarchies: Developers must understand and maintain both the creator hierarchy and the product hierarchy.
  • Inheritance constraints: The pattern relies on inheritance. This can make the design less flexible when creation behaviour needs to vary independently of the creator's class hierarchy.
  • Potential over-engineering: For simple object creation, a factory delegate, a small factory class or dependency injection may be easier to understand and maintain.

The key is to recognise when the flexibility provided by the pattern justifies the additional structure.

Factory Method in modern .NET applications

The classic Factory Method remains useful, but it is not the only way to manage object creation in modern .NET applications.

The built-in dependency injection container provides alternatives that can solve similar problems without requiring a separate creator subclass for every implementation.

Understanding these alternatives helps us distinguish the GoF pattern from everyday object-creation techniques.

Keyed services

Keyed services, introduced in .NET 8, allow multiple implementations of the same interface to be registered using different keys.

For example:

builder.Services.AddKeyedScoped<
    INotificationSender,
    EmailNotificationSender>("email");

builder.Services.AddKeyedScoped<
    INotificationSender,
    SmsNotificationSender>("sms");

A consumer can request a specific implementation using the [FromKeyedServices] attribute:

public class EmailNotificationService(
    [FromKeyedServices("email")]
    INotificationSender sender)
{
    public void Send(string message)
    {
        sender.Send(message);
    }
}

This is useful when the required implementation is known when the dependency is injected.

Instead of creating separate creator subclasses, the dependency injection container resolves the registered implementation using its key.

Factory delegates

The .NET dependency injection container also supports factory delegates during service registration.

These allow us to define how an implementation should be constructed, including cases where the choice depends on configuration.

builder.Services.AddScoped<INotificationSender>(
    serviceProvider =>
    {
        var configuration = serviceProvider
            .GetRequiredService<IConfiguration>();

        var channel = configuration[
            "Notifications:DefaultChannel"];

        return channel switch
        {
            "email" => ActivatorUtilities.CreateInstance<
                EmailNotificationSender>(serviceProvider),

            "sms" => ActivatorUtilities.CreateInstance<
                SmsNotificationSender>(serviceProvider),

            _ => throw new InvalidOperationException(
                "Unsupported notification channel.")
        };
    });

Here, the application reads its configured notification channel and creates the appropriate implementation.

ActivatorUtilities.CreateInstance allows the object to be constructed while resolving its dependencies from the service provider.

This approach is useful when construction requires a small amount of conditional logic or configuration.

Which approach should you choose?

These techniques solve related problems, but they are not interchangeable definitions of Factory Method.

Approach Best suited to
Classic Factory Method Subclasses need to customise object creation while preserving a shared workflow defined by a base creator
Keyed services Multiple implementations need to be registered and resolved using a key
Factory delegates Object construction depends on configuration or a small amount of conditional logic
Simple Factory A centralised class or method selects and returns an implementation

Use the classic GoF pattern when inheritance-based customisation is genuinely useful, particularly when designing extensible frameworks or reusable components.

Use keyed services when the application simply needs to resolve one of several registered implementations. Use factory delegates when construction requires a small amount of decision-making.

The important principle is to choose the simplest approach that keeps object creation understandable and business logic independent of concrete implementations.

Factory Method versus Simple Factory and Abstract Factory

These three concepts are often confused because they all deal with object creation.

However, they solve different problems.

Simple Factory

A Simple Factory centralises object creation in a method or class. It typically uses a conditional or lookup to decide which concrete implementation to return.

It can be a perfectly reasonable solution when the creation logic is straightforward. However, it is not the classic GoF Factory Method because it does not rely on subclasses overriding a creation method.

Factory Method

Factory Method defines a creation method in a creator class and allows subclasses to determine which concrete product is returned.

The creator typically contains business logic that uses the product abstraction.

Abstract Factory

Abstract Factory provides an interface for creating families of related objects without specifying their concrete classes.

For example, if our ticket management application eventually supports different notification providers, each with its own message formatter, delivery client and configuration, Abstract Factory could provide a way to create a compatible family of notification components.

The main distinction is that Factory Method focuses on allowing subclasses to customise the creation of a product, while Abstract Factory focuses on creating families of related products.

Conclusion

Factory Method is useful when a class needs to perform a consistent workflow, but the concrete objects used by that workflow must vary.

By moving the creation decision into an overridable method, the pattern separates object construction from the business logic that uses the resulting object.

However, it comes with a cost: additional classes, inheritance relationships, and maintenance overhead.

In modern .NET applications, dependency injection, keyed services, and factory delegates often provide simpler ways to manage object creation. The classic pattern is still valuable when its inheritance-based extension mechanism solves a real problem.

As with the SOLID principles, the goal is not to introduce abstractions for their own sake. It is to make software easier to extend, understand, and maintain.

In the next article, we'll explore Abstract Factory, a pattern that takes object creation further by providing a way to create families of related objects without coupling the application to their concrete implementations.

Further reading

Books

  • Dive Into Design Patterns — Alexander Shvets. See the Creational Design Patterns chapter on Factory Method.
  • Design Patterns in C#, Second Edition — Vaskaran Sarcar. See the Factory Method chapter for additional C# examples.

Online resources

No comments yet. Be the first to comment.