策略模式中的变化参数

发布于 2024-12-18 05:58:42 字数 587 浏览 1 评论 0原文

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

例如,

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

硪扪都還晓 2024-12-25 05:58:42

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

另外,另一种选择是创建一个 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文