Created
February 3, 2016 07:32
-
-
Save sudipto80/6678ab20e674e9612056 to your computer and use it in GitHub Desktop.
Strategy Pattern
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
using System; | |
using System.Collections.Generic; | |
namespace DoFactory.GangOfFour.Strategy.RealWorld | |
{ | |
/// <summary> | |
/// MainApp startup class for Real-World | |
/// Strategy Design Pattern. | |
/// </summary> | |
class MainApp | |
{ | |
/// <summary> | |
/// Entry point into console application. | |
/// </summary> | |
static void Main() | |
{ | |
// Two contexts following different strategies | |
SortedList studentRecords = new SortedList(); | |
studentRecords.Add("Samual"); | |
studentRecords.Add("Jimmy"); | |
studentRecords.Add("Sandra"); | |
studentRecords.Add("Vivek"); | |
studentRecords.Add("Anna"); | |
studentRecords.SetSortStrategy(new QuickSort()); | |
studentRecords.Sort(); | |
studentRecords.SetSortStrategy(new ShellSort()); | |
studentRecords.Sort(); | |
studentRecords.SetSortStrategy(new MergeSort()); | |
studentRecords.Sort(); | |
// Wait for user | |
Console.ReadKey(); | |
} | |
} | |
/// <summary> | |
/// The 'Strategy' abstract class | |
/// </summary> | |
abstract class SortStrategy | |
{ | |
public abstract void Sort(List<string> list); | |
} | |
/// <summary> | |
/// A 'ConcreteStrategy' class | |
/// </summary> | |
class QuickSort : SortStrategy | |
{ | |
public override void Sort(List<string> list) | |
{ | |
list.Sort(); // Default is Quicksort | |
Console.WriteLine("QuickSorted list "); | |
} | |
} | |
/// <summary> | |
/// A 'ConcreteStrategy' class | |
/// </summary> | |
class ShellSort : SortStrategy | |
{ | |
public override void Sort(List<string> list) | |
{ | |
//list.ShellSort(); not-implemented | |
Console.WriteLine("ShellSorted list "); | |
} | |
} | |
/// <summary> | |
/// A 'ConcreteStrategy' class | |
/// </summary> | |
class MergeSort : SortStrategy | |
{ | |
public override void Sort(List<string> list) | |
{ | |
//list.MergeSort(); not-implemented | |
Console.WriteLine("MergeSorted list "); | |
} | |
} | |
/// <summary> | |
/// The 'Context' class | |
/// </summary> | |
class SortedList | |
{ | |
private List<string> _list = new List<string>(); | |
private SortStrategy _sortstrategy; | |
public void SetSortStrategy(SortStrategy sortstrategy) | |
{ | |
this._sortstrategy = sortstrategy; | |
} | |
public void Add(string name) | |
{ | |
_list.Add(name); | |
} | |
public void Sort() | |
{ | |
_sortstrategy.Sort(_list); | |
// Iterate over list and display results | |
foreach (string name in _list) | |
{ | |
Console.WriteLine(" " + name); | |
} | |
Console.WriteLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment