Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Strategy design pattern example
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.