Strategy pattern lets clients parameterizing algorithm and leave the choice of selecting the algorithm to the user.
What is the practical usage of this pattern? I have written many lines of code with many if statement to determine the object type, dynamically load it, and then call one the method to do the job. In this specific scenario, Strategy pattern would provide a much more elegant, flexible and extensible approach.
Array and ArrayList in NET use this pattern for sorting stored objects.
Let's look at the coding structure of this pattern:
using System;
// This can also be an abstract class if you prefer
interface IDocument
{
void Load();
}
class TextFile : IDocument
{
public void Load()
{
Console.WriteLine("TextFile.Load()");
}
}
class XmlFile : IDocument
{
public void Load()
{
Console.WriteLine("XmlFile.Load()");
}
}
class Context
{
IDocument strategy;
public Context( IDocument strategy )
{
this.strategy = strategy;
}
public void Load()
{
strategy.Load();
}
}
public class Client
{
public static void Main( string[] args )
{
Context Text = new Context(new TextFile());
Text.Load();
Context Xml = new Context(new XmlFile());
Xml.Load();
}
}
Here is a summary of the structural concept of the Strategy pattern:
1. Create an interface and declare a method. You can use base class if you prefer.
2. Create classes that implemnent the interface
3. Create a context class (rename context to anything you want) to hold a reference to the object interface and add a method with logic to invoke the interface method
4. Client can now create an instance of the context class to accept an algorithm(object) as a parameter. Use the parameterized object to call the appropriate method to perform the task
Anyone has any idea to use it differently or has a different view about this pattern, love to hear from you.
Hope it helps