2011-11-25 80 views
9

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

例如

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 
    } 

} 

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

回答

9

这通常是可以接受的,虽然如果只有某些实现需要参数,也许将这些参数提供给实现的构造函数会更有意义(即将它们留在策略接口之外),但这可能不会成为你的情况的一个选择。

此外,另一种选择是制作一个Parameters类,并让您的策略方法简单地采取其中之一。这个类然后可以有各种参数的获得者(即int num),如果一个特定的实现不需要使用num那么它就不会调用parameters.getNum()。这也使您可以灵活地添加新参数,而无需更改任何现有的策略实施或接口。

就是这样说,像Parameters这样的类让我觉得在其他地方出现了抽象失败的情况,尽管有时候你只能让它工作。