策略模式中的参数不同

blu*_*sky 10 design-patterns strategy-pattern

有时在使用策略模式时,我发现一些算法实现不需要相同的参数列表.

例如

    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
     }

}
Run Code Online (Sandbox Code Playgroud)

我应该使用不同的设计模式吗?

Nat*_* W. 10

这通常是可以接受的,尽管如果某些实现只需要参数,也许将它们提供给实现的构造函数会更有意义(即将它们排除在策略接口之外),尽管这可能不是一个选项.你的情况.

另外,另一个选择是创建一个Parameters类,让你的策略方法只需要其中一个.然后这个类可以有各种参数的getter(即int num),如果某个特定的实现不需要使用num那么它根本就不会调用parameters.getNum().这也使您可以灵活地添加新参数,而无需更改任何现有的策略实现或接口.

话虽如此,一个类似的Parameters让我觉得在其他地方有抽象失败,尽管有时候你只需要让它工作.