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 Sr. Software Developer at Kunz, Leigh, & Associates in Okemos, MI. 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 vogelvision@gmail.com.

comments powered by Disqus

Reader Comments:

Tue, Jul 17, 2012 Tim Ellison Richmond, VA

Great example of using Strategy pattern for validation of different types of people (or could have been different specializations of > Person). From a patterns POV, you'd most likely couple this with a Factory Method or as you mentioned, inject the dictionary into the context (Client). I've used this approach many times with Spring.NET and with great success.

Wed, Apr 18, 2012 Brian

Another way to get the implmentation you want is to use an abstract base class instead of an interface. The various implementations derive from this abstract base class, but it also includes a static method to return the concrete class that is appropriate to the context - a factory method in other words.

Wed, Mar 21, 2012 mirza faishal beg delhi

.net is a platform...........

Thu, Mar 15, 2012 MarkSpiez

In response to the previous post: You've asked a very good OOP design question. What you've implemented is called the Bridge Pattern which differs only in "intent" of what it is you're designing and how you want a "client" to interact with your code. Without going into great length since the topic has been defined before, here are some links on the subjet. http://en.wikipedia.org/wiki/Strategy_pattern#Strategy_versus_Bridge http://game-engineering.blogspot.com/2008/07/bridge-pattern-vs-strategy-pattern.html So your solution is perfectly acceptable, but so is the one defined in the article. I think many times in tutorial articles, the excersize is so simple it's easy to argue alternative ways to implement rather than just focus on the topic of how to do implement. It would be nice to see more authors include "intent" and "when to use" sections of the subject, rather then just a "how to".

Wed, Mar 14, 2012

dumb question. what is wrong with: public interface iPerson { string firstname {get; set;} string lastname {get; set;} datetime? dateofbirth{get; set;} int ssn {get; set;} int ein {get; set;} bool isValid(){} } public class person : iPerson { public string firstname {get; set;} public string lastname {get; set;} public datetime? dateofbirth{get; set;} public int ssn {get; set;} public int ein {get; set;} public virtual bool isValid(){} } public class employer:person, iPerson { public override bool isValid(){} } public class employee:person, iPerson { public override bool isValid(){} } public class customer:person, iPerson { public override bool isValid(){} } ... other than my capitalization? ;-) I know it may not implement the strategy pattern, but why is the strategy pattern demonstrated a better solution than what I show above?

Wed, Mar 7, 2012 Chip

In Listing 5, both the Employee and Customer PersonType's are paired with the EmployeeValidationStrategy in the Dictionary. I assume this is a typo and PersonType.Customer should be paired with CustomerValidationStrategy?

Thu, Feb 23, 2012 JF Portland OR

The memory is not that big of an issue as the dictionalry is static. However, what could be an issue is that the dictionary and its contents are replaced every time an instance is created. This could cause threading or other issues. Two ways around this that I can think of quickly. Build the dictionary in a static constructor, or ditch the dictionary and inject an instance of the interface implementation on object instance creation (Unity etc..). Also, I would think that the person class should implement the interface; ie Person : IPersonValidationStrategy. My two cents.

Thu, Feb 23, 2012 Jason

The way you assigned the implementing class to the interface was interesting (Listing 5). I usually just use a switch statement because it doesn't require any objects to be in memory like your dictionary. If you have a list of lets say 10000 Person objects the memory used for _validationStategies wouldn't really be necessary. What would be some other ways to accomplish listing 5 besides the way you did it or a switch statement?

Add Your Comments Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.