Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Wednesday
Jan282009

C# Design patterns: the Strategy pattern

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();
        }
    }
}

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« Unix Cheat Sheet | Main | C# Design Patterns: the Iterator pattern »