Musings
Public · Protected · Private
Strategy
-
2008-04-13 02:23whenever i want to drive from place A to place B , I want driving directions. But before going for directions, I have one more Question(context)-- how much time I have? 1) Don't have much time -- Get Least time path. 2)Have enough time -- Get Least distance 'directions' 3) Too much time -- what else can I do on the way?? For the same task of "Get driving directions" our strategy changes acording to the context.
-
2008-04-13 02:24abstract class SortStrategy { public abstract void Sort(ArrayList list); } class QuickSort : SortStrategy { public override void Sort(ArrayList list) { list.Sort(); // Default is Quicksort Console.WriteLine("QuickSorted list "); } } class ShellSort : SortStrategy { public override void Sort(ArrayList list) { //list.ShellSort(); not-implemented Console.WriteLine("ShellSorted list "); } } class MergeSort : SortStrategy { public override void Sort(ArrayList list) { //list.MergeSort(); not-implemented Console.WriteLine("MergeSorted list "); } } class SortedList { private ArrayList list = new ArrayList(); 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); // Display results foreach (string name in list) { Console.WriteLine(" " + name); } Console.WriteLine(); } } In the above example the strategy is decided at runtime.
-
2008-04-13 03:10Example: humans animals and birds are three classes derived from Creatures All have Eat() method Drink() Walks() Jump() mehods So bird or animal or human should implement Eat() Let me create three other classes. 1) class HowEverEat 2) class EatWithMouth : HowEverEat 3) class EatWithNose : HowEverEat and our animals just contain a pointer to HoweverEat and they implement their Eat() as Eat() { myHowEverEat.Eat(); } So at runtime we decide how to Eat() Understanding: Many a times we create diferent classes that have different intelligence. But sometimes we come across some actions (methods of class) that can be done differently -- or we feel some intelligence(properties) belongs more to the actions than to the objects. Typically Strategy allows Contextsensitive approach to a method. Here method is implemented in an interface (Note: interface here needs to become an class that really implements)
This blog is frozen. No new comments or edits allowed.