Using the strategy pattern, how can treat different exectute methods
differently in terms of them having different parameters?
If you make it work this way, it won't be considered a strategy
pattern. The fact that your client knows different strategies require different parameters, invalidates the strategy pattern, because then client is assumed to know (at least partially) what specific strategy does internally.
Understand that strategy should not accept parameters selectively. It should instead work on the parameters selectively. So until you read further down, consider that we now have all strategies accepting all parameters. So that Strategy1
uses only param1
and param2
and ignores param3
, and so on.
function execute(param1, param2, param3) { }
However this gets ugly if you have even more parameters. You can instead have a separate Parameter
class and pass this collection of parameters to every strategy. Each strategy will include a logic to get and use parameters that it requires and will ignore rest.
then they do something generic that every strategy will do
That's what you can have abstract strategy for. It will include abstract execute()
method and it's own execute()
method that each concrete strategy will call.
To summarize, here's how it would look like (non-compilable code):
Main()
{
AbstractStrategy s = new ConcreteStrategy1();
s.Execute(parameters); // parameters -> collection
}
class AbstractStrategy {
Execute(parameters); // abstract
Execute() {} // not public
}
class ConcreteStrategy1 : AbstractStrategy {
override Execute(parameters) {
string pvalue1 = parameters.GetValue("param1");
base.Execute();
}
}