I have three types of algorithms, each take a different parameter type needed for prcoessing.
class AlgorithmA
{
Execute(int param);
}
class AlgorithmB
{
Execute(string param);
}
class AlgorithmC
{
Execute();
}
to employ the strategy pattern with MEF, I did the following:
interface IAlgorithm
{
int IntegerParam{get;set;}
string StringParam{get;set;}
string AlgorithmName {get;}
void Execute();
}
and in the client:
[ImportMany]
IEnumerable<IAlgorithm> Algorithms { get; set; }
IAlgorithm algorithm=Algorithms.Single(a => a.AlgorithmName == name);
algorithm.IntegerParam=integerParam;
algorithm.StringParam=stringParam;
algorithm.Execute();
now the question is, it’s obviously wrong to supply necessary parameters as properties, but on the other hand, if i supply them as constructor parameters, it will defeat the very purpose of the pattern.
what would you do ?
The strategy pattern should pass the same parameters to its strategies, regardless of the one that was actually chosen; then, each strategy should decide what to do with these parameters.
In case you need to pass two parameters, you should probably define something like this:
Then if a certain strategy only needs to use the first parameter, then it simply uses it and ignores the other parameter.
What I think you’re missing is that if you try to pass different parameters to different strategies then you’re pretty much giving up on the strategy here, because you already know something about the strategy being used, how it works internally and what it needs.