有时在使用策略模式时,我发现一些算法实现不需要相同的参数列表。
例如
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
}
}
我应该使用不同的设计模式吗?
最佳答案
这通常是可以接受的,尽管如果存在仅某些实现需要的参数,也许将这些参数提供给实现的构造函数会更有意义(即,将它们排除在策略接口(interface)之外),尽管这可能不是一个选项你的情况。
此外,另一种选择是制作 Parameters
上课并让您的策略方法简单地采用其中之一。然后,此类可以具有各种参数的 getter(即 int num
),如果特定实现不需要使用 num
那么它根本不会调用parameters.getNum()
.这也使您可以灵活地添加新参数,而无需更改任何现有的策略实现或接口(interface)。
话虽如此,像 Parameters
这样的类让我觉得在其他地方出现了抽象失败,尽管有时你只需要让它工作。
关于design-patterns - 策略模式中的变化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8274885/