C# Corner
The Strategy Pattern in .NET
Eric Vogel shows you how to use a common software design pattern that allows an app to dynamically pick an appropriate method at runtime.
Developers often run into similar problems when architecting software. To help tackle this problem, software design patterns have become quite popular. The Strategy Pattern is a common design pattern that allows an application to dynamically pick an appropriate method at runtime based on its host's context.
The Strategy pattern has three core pieces: a context, a strategy interface and one or many strategy implementations. The strategy interface defines the contract that will be used by each of the strategy implementations. The context class contains an interface member that is assigned to a concrete implementation at run-time to select the strategy to use.
One common usage of the Strategy pattern is as a replacement for a complex switch-case statement. For example, say you have a Person class that has specific validation logic depending on the PersonType of the person. You may start out by putting this logic into a switch-case statement as shown in Listing 1.
The individual validation logic is not very complex at this point, but it has the potential to grow unwieldy with the addition of new requirements and new fields to validate. To tackle this issue of complexity, you can break up each person type validation into its own class, which is responsible for validating its person type. When, and if, the person type changes, you can adapt and pick the correct strategy to meet your domain needs.
To get started, I'll create a common interface for validation called IPersonValidationStrategy that contains one IsValid method that accepts a Person entity:
using System;
namespace VSMStrategyPatternDemo
{
public interface IPersonValidationStrategy
{
bool IsValid(Person person);
}
}
Now you can break up the validation for each person type into separate concrete classes that each implement the IValidationStrategy interface. See Listings 2, 3, and 4 for the concrete employer, employee and customer validation strategies respectively.
Next, I update the Person class to use an IValidationStrategy to perform its validation over the old switch-case statement. I have added a Dictionary<PersonType,IValidationStrategy> that creates the bindings to the concrete strategies in Person constructor. The IsValid method has been updated to then call the matching concrete strategy via the PersonType key of the object. This technique is often referred to as dispatching. Refer to Listing 5 for the fully updated Person class that acts as the context triad of the Strategy pattern.
As you can see, the validation code was cleaned up quite a bit and is also more extensible. Now you can safely make changes to the validations for person types without having to modify the IsValid method at all. You can also swap out strategies for a PersonType through the Person constructor. To go one step further, you could use dependency injection and retrieve the dictionary of validation strategies through an Inversion of Control (IoC) Framework such as Autofac, Ninject, StructureMap or Unity. If you chose to use an IoC container to inject the mappings, it's best to add the PersonType to the IPersonValidationStrategy interface as follows:
using System;
namespace VSMStrategyPatternDemo
{
public interface IPersonValidationStrategy
{
bool IsValid(Person person);
PersonType Type { get; }
}
}
You could then alter the concrete implementations for the strategies to return the appropriate PersonType per implementation. From there you could retrieve all classes in your assemblies that implement the IPersonValidationStrategy interface and add them by their PersonType key to the _validationStategies dictionary. The rest of the Person class code would remain unchanged.
The Strategy Pattern is a good way to make sure your code follows the open-closed principle: your code is open to extensibility, but closed to modification. It's a suitable replacement for a switch-case statement or complex conditional logic within a method. It also leads to more testable code, especially when coupled with IoC.
About the Author
Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].