Skip to content

Instantly share code, notes, and snippets.

@rbwestmoreland
Created January 15, 2012 17:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbwestmoreland/1616581 to your computer and use it in GitHub Desktop.
Save rbwestmoreland/1616581 to your computer and use it in GitHub Desktop.
Properly Implementing the Strategy Pattern
using System;
/// <summary>
/// The context, which consumes a strategy.
/// </summary>
public class Context
{
protected IStrategy Strategy { get; set; }
public Context(IStrategy strategy)
{
Strategy = strategy;
}
public virtual void DoWork()
{
Strategy.DoWork();
}
}
using System;
/// <summary>
/// The strategy's interface.
/// <para>The Strategy pattern is a behavioral pattern, whose
/// purpose is to define a family of algorithms, encapsulate
/// each one, and make them interchangeable. Strategy lets
/// the algorithm vary independently from clients that use
/// it.</para>
/// </summary>
public interface IStrategy
{
void DoWork();
}
using System;
/// <summary>
/// Concrete strategy A
/// </summary>
public class StrategyA : IStrategy
{
public virtual void DoWork()
{
// Do work this way.
}
}
using System;
/// <summary>
/// Concrete strategy B
/// </summary>
public class StrategyB : IStrategy
{
public virtual void DoWork()
{
// Do work that way.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment