Sometimes when using the strategy pattern I find some of the algorithm implementations do not require the same parameter list.
For example
public interface Strategy{
public void algorithm(int num);
}
public class StrategyImpl1 implements Strategy{
public void algorithm(int num){
//num is needed in this implementation to run algorithm
}
}
public class StrategyImpl2 implements Strategy{
public void algorithm(int num){
//num is not needed in this implementation to run algorithm but because im using same
strategy interface I need to pass in parameter
}
}
Is there a different design pattern I should use ?
This is generally acceptable, although if there are parameters that are only needed by some implementations, perhaps it would make more sense to provide those to the implementation's constructor (i.e. leave them out of the strategy interface), although this may not be an option in your situation.
Also, another option is to make a Parameters
class and have your strategy method simply take one of these. This class can then have getters for various parameters (i.e. int num
), and if a particular implementation doesn't need to use num
then it simply won't call parameters.getNum()
. This also gives you flexibility in adding new parameters without having to change any existing strategy implementations or interfaces.
With that said, a class like Parameters
leaves me feeling like there's been an abstraction failure somewhere else, although sometimes you just gotta make it work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With