Created
January 15, 2012 17:54
-
-
Save rbwestmoreland/1616581 to your computer and use it in GitHub Desktop.
Properly Implementing the 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; | |
/// <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(); | |
} | |
} |
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; | |
/// <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(); | |
} |
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; | |
/// <summary> | |
/// Concrete strategy A | |
/// </summary> | |
public class StrategyA : IStrategy | |
{ | |
public virtual void DoWork() | |
{ | |
// Do work this way. | |
} | |
} |
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; | |
/// <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