Last active
December 12, 2015 08:48
-
-
Save yetanotherchris/4746350 to your computer and use it in GitHub Desktop.
Strategy design pattern example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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