Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varying parameters in strategy pattern

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 ?

like image 931
blue-sky Avatar asked Nov 25 '11 22:11

blue-sky


1 Answers

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.

like image 123
Nate W. Avatar answered Nov 11 '22 21:11

Nate W.