You mention the possibility of simply using lambdas in C#. For strategies with few steps, this is often idiomatic. It can be really convenient:
let f step1 step2 =
let i = 4
// ...
let s = step1 i
// ...
let d = step2 s
// ...
d
No need for interface definitions or object expressions; the inferred types of step1
and step2
is enough. In languages without higher-order functions (which is the setting in which the Strategy Pattern was invented, I believe), you don't have this option and need instead, e.g., interfaces.
The function f
here presumably doesn't care if step1
and step2
are related. But if the caller does, nothing is preventing him from bundling them up in a data structure. E.g., using @pad's answer,
let x = f strategyA.Step1 strategyA.Step2
// val it = 0.0
In general, the "idiomatic way" depends on why you are considering the Strategy Pattern in the first place. The Strategy Pattern is about stitching together functionality; higher-order functions are often really good for that too.