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 preferinterface 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 interface3. 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
doesnt this pattern already have another name..
erm.. wat was it...
xtreme.net wrote: doesnt this pattern already have another name.. erm.. wat was it...
You mean 'Policy'?
Strategy Pattern the Generics Way:
class AccountContext<T> where T: IStrategyAccount,new() { T account; public AccountContext() { this.account = new T(); } public float Compute(int amt) { return account.Compute(amt); } } interface IStrategyAccount { float Compute(float amt); } class LifeSaverAccount : IStrategyAccount { private float _interest = 0.05F; #region IStrategyAccount Members public float Compute(float amt) { return _interest * amt; } #endregion } class StudentAccount : IStrategyAccount { private float _interest = 0.02F; public float Compute(float amt) { return (_interest * amt)*1.005F ; } } class AccountManager { static void Main(String[] args) { AccountContext<LifeSaverAccount> ctx = new AccountContext<LifeSaverAccount>(); Console.WriteLine("${0} computed.",ctx.Compute(5000)); } }