Last active
          August 29, 2015 14:21 
        
      - 
      
 - 
        
Save odennZero/b913f9bebdba7a267528 to your computer and use it in GitHub Desktop.  
    Strategy Pattern Example
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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