Class Strategy<TIn, TOut>
- Namespace
- PatternKit.Behavioral.Strategy
- Assembly
- PatternKit.Core.dll
Represents a "first-match-wins" strategy pipeline built from predicate/handler pairs.
public sealed class Strategy<TIn, TOut>
Type Parameters
TInThe input type accepted by each predicate and handler.
TOutThe output type produced by a matching handler.
- Inheritance
-
Strategy<TIn, TOut>
- Inherited Members
- Extension Methods
Examples
var strategy = Strategy<int, string>.Create()
.When(static i => i > 0).Then(static i => "positive")
.When(static i => i < 0).Then(static i => "negative")
.Default(static _ => "zero")
.Build();
var label = strategy.Execute(5); // "positive"
Remarks
Strategy<TIn, TOut> is a simpler, non-out-based variant of
TryStrategy<TIn, TOut>. It uses Strategy<TIn, TOut>.Predicate delegates to
decide whether a handler applies, and Strategy<TIn, TOut>.Handler delegates to produce the
result. The first predicate that returns true determines which
handler is executed.
If no predicates match and no default handler is configured, an InvalidOperationException is thrown via NoStrategyMatched<T>().
Methods
Create()
Creates a new Strategy<TIn, TOut>.Builder for constructing a Strategy<TIn, TOut>.
public static Strategy<TIn, TOut>.Builder Create()
Returns
- Strategy<TIn, TOut>.Builder
A new Strategy<TIn, TOut>.Builder instance.
Examples
var s = Strategy<string, string>.Create()
.When(s => string.IsNullOrEmpty(s)).Then(_ => "empty")
.Default(_ => "other")
.Build();
var result = s.Execute(""); // "empty"
Execute(in TIn)
Executes the strategy pipeline against the given input.
public TOut Execute(in TIn input)
Parameters
inputTInThe input value.
Returns
- TOut
The result from the first matching handler, or the Default(Handler) result if provided.
Remarks
Iterates the registered predicates in the order they were added. The first predicate that returns true causes its corresponding handler to execute and the method returns immediately.
If no predicate matches:
- If a default handler is set, its result is returned.
- Otherwise, NoStrategyMatched<T>() is called, which always throws.
Exceptions
- InvalidOperationException
Thrown when no predicates match and no default handler is configured.