Skip to content

Instantly share code, notes, and snippets.

@odennZero
Last active August 29, 2015 14:21
Show Gist options
  • Save odennZero/b913f9bebdba7a267528 to your computer and use it in GitHub Desktop.
Save odennZero/b913f9bebdba7a267528 to your computer and use it in GitHub Desktop.
Strategy Pattern Example
public class Librarian {
// librarian sort strategy storage
protected ISortStrategy sortStrategy;
public void SetSortType(ISortStrategy sortStrategy) {
this.sortStrategy = sortStrategy;
}
public void SortBooks(List<Books> books) {
if (sortStrategy != null)
sortStrategy.Sort(List<Books> books);
}
}
// sort interface
public interface ISortStrategy {
void Sort(List<Books> books);
}
public class SortAlpha : ISortStrategy {
public void Sort(List<Books> books) {
// alphabetical sort
}
}
public class SortDate : ISortStrategy {
public void Sort(List<Books> books) {
// publish date sort
}
}
// example use
public class Program {
public static void Main(string[] args) {
var books = new List<Books>();
var lib = new Librarian();
lib.SetSortType(new SortAlpha());
lib.SortBooks(books); // sorts the books alphabetically
lib.SetSortType(new SortDate());
lib.SortBooks(books); // sorts the books by publication date
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment