Chris's coding blog

C# Design patterns: the Strategy pattern

January 28, 2009

Summary

Multiple classes implement an interface, handling an algorithm in a different way.

Example

Sorting is the clearest working example of the Strategy pattern. In .NET you’ll find it in the IComparer interface alongside Array.Sort/LINQ, see the links section for an article on this on MSDN.

namespace DesignPatterns
{
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", Name, Age);
}
}
/// <summary>
/// Compares two users based on name.
/// </summary>
public class NameSorter : IComparer<User>
{
public int Compare(User x, User y)
{
return x.Name.CompareTo(y.Name);
}
}
/// <summary>
/// Compares two Users based on their age.
/// </summary>
public class AgeSorter : IComparer<User>
{
public int Compare(User x, User y)
{
return x.Age.CompareTo(y.Age);
}
}
/// <summary>
/// A simple extension method class for pretty-printing the
/// List<Users> collection.
/// </summary>
public static class ListExtension
{
public static string Print(this List<User> list)
{
StringBuilder builder = new StringBuilder();
foreach (User user in list)
{
builder.AppendLine(user.ToString());
}
return builder.ToString();
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharpdesign-patterns

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume