Table of Contents

Class StrategyContext<TContext, TResult>

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

TContext

Input type for the strategy.

TResult

Output 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

initialStrategy IStrategy<TContext, TResult>

The strategy to use until replaced.

Methods

ExecuteStrategy(TContext)

Delegates execution to the currently active strategy.

public TResult ExecuteStrategy(TContext context)

Parameters

context TContext

Input 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

strategy IStrategy<TContext, TResult>

The new strategy to use from this point on.