Strategy Pattern
Post Series: Behavioral Design Pattern
This pattern allows a client to choose an algorithm from a family of algorithms at run-time and gives it a simple way to access it.
- Client: This is a class that contains a property to hold the reference of a Strategy object. This property will be set at run-time according to the algorithm that is required.
- Strategy: This is an interface that is used by the Context object to call the algorithm defined by a ConcreteStrategy.
- ConcreteStrategyA/B: These are classes that implements Strategy interface.
Implement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class Client { public IStrategy Strategy { get; set; } public void CallAlgorithm() { Console.WriteLine(Strategy.Algorithm()); //Call at runtime } } public interface IStrategy { string Algorithm(); } public class ConcreteStrategyA : IStrategy { public string Algorithm() { return "Concrete Strategy A"; } } public class ConcreteStrategyB : IStrategy { public string Algorithm() { return "Concrete Strategy B"; } } |
Example
When to use it?
- There are multiple strategies for a given problem and the selection criteria of a strategy is defined a run-time.
- Many related classes are only differ in their behaviors.
- The strategies use the data to which the client has no access.
Resource
http://www.dotnettricks.com/learn/designpatterns/strategy-design-pattern-c-sharp