Class StrategyContext<TContext, TResult>
- Namespace
- WitShells.DesignPatterns.Core
The Context class in the Strategy pattern. Holds a reference to the current strategy and delegates execution to it. The active strategy can be swapped at runtime via SetStrategy(IStrategy<TContext, TResult>).
public class StrategyContext<TContext, TResult>
Type Parameters
TContextInput type for the strategy.
TResultOutput type returned by the strategy.
- Inheritance
-
StrategyContext<TContext, TResult>
- Inherited Members
Examples
var ctx = new StrategyContext<(int,int), int>(new AddStrategy());
int sum = ctx.ExecuteStrategy((3, 4)); // 7
ctx.SetStrategy(new MultiplyStrategy());
int product = ctx.ExecuteStrategy((3, 4)); // 12
Constructors
StrategyContext(IStrategy<TContext, TResult>)
Initialises the context with a starting strategy.
public StrategyContext(IStrategy<TContext, TResult> initialStrategy)
Parameters
initialStrategyIStrategy<TContext, TResult>The strategy to use until replaced.
Methods
ExecuteStrategy(TContext)
Delegates execution to the currently active strategy.
public TResult ExecuteStrategy(TContext context)
Parameters
contextTContextInput data for the strategy.
Returns
- TResult
The result produced by the active strategy.
Exceptions
- InvalidOperationException
Thrown when no strategy has been set.
SetStrategy(IStrategy<TContext, TResult>)
Replaces the current strategy at runtime.
public void SetStrategy(IStrategy<TContext, TResult> strategy)
Parameters
strategyIStrategy<TContext, TResult>The new strategy to use from this point on.