策略模式中的变化参数
有时,在使用策略模式时,我发现某些算法实现不需要相同的参数列表。
例如,
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
}
}
我应该使用不同的设计模式吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这通常是可以接受的,尽管如果存在仅某些实现需要的参数,则将这些参数提供给实现的构造函数可能更有意义(即,将它们保留在策略接口之外),尽管这可能不是一个选项你的情况。
另外,另一种选择是创建一个
Parameters
类,并让您的策略方法仅采用其中一个。然后,此类可以具有各种参数的 getter(即int num
),并且如果特定实现不需要使用num
那么它就不会调用parameters.getNum()
。这还使您可以灵活地添加新参数,而无需更改任何现有的策略实现或接口。话虽如此,像
Parameters
这样的类让我感觉好像在其他地方出现了抽象失败,尽管有时您只需让它工作即可。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 usenum
then it simply won't callparameters.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.