java中用于实现具有相似签名的大量方法的最佳设计模式是什么?

时间:2012-11-16 18:49:35

标签: java design-patterns

我想实现以下类中的所有cdl(烛棒模式)方法 TA-Lib

大约有61种cdl分析方法,其中约90%具有相似的签名,只是它们的核心实现不同。

例如:

 public RetCode cdl2Crows(int startIdx,
      int endIdx,
      double inOpen[],
      double inHigh[],
      double inLow[],
      double inClose[],
      MInteger outBegIdx,
      MInteger outNBElement,
      int outInteger[])


public RetCode cdl3BlackCrows(int startIdx,
      int endIdx,
      double inOpen[],
      double inHigh[],
      double inLow[],
      double inClose[],
      MInteger outBegIdx,
      MInteger outNBElement,
      int outInteger[])

我在想是否可以将方法名称作为参数从我的源类传递,然后使用反射调用方法,以避免重复的代码

public invokeAnalytic(String analyticMethodName, common params .....)
{
    // using reflection invoke analyticMethodName of Core class
    // and pass rest of the params
}
  1. 这种情况下java中最好的设计模式是什么?
  2. 如果我在这种情况下使用反射,是否会出现性能问题?

5 个答案:

答案 0 :(得分:2)

如何将参数包装在不可变的Value Object

E.g。

MyValueObject params = new MyValueObject(int startIdx,
    int endIdx,
    double inOpen[],
    double inHigh[],
    double inLow[],
    double inClose[],
    MInteger outBegIdx,
    MInteger outNBElement,
    int outInteger[]);

// ....
someObject.cdl2Crows(params);
// ...
someObject.cdl3BlackCrows(params);

答案 1 :(得分:1)

创建公共数据点的最终类(类似于C中的结构)并将其作为参数传递给函数。它有点沉重,但没有你想象的那么糟糕(特别是如果类被声明为final)。

答案 2 :(得分:1)

public interface CDL

    public RetCode invoke
    (
          int startIdx,
          int endIdx,
          double inOpen[],
          double inHigh[],
          double inLow[],
          double inClose[],
          MInteger outBegIdx,
          MInteger outNBElement,
          int outInteger[]
    );

static Map<String,CDL> map = new HashMap<>();


map.put("cdl2Crows", new CDL()
{ 
    public RetCode invoke(...)
    { 
        impl... 
    }
});
...

答案 3 :(得分:0)

在这种情况下应该避免反思,因为你不会输入更少的安全性和性能。

在这种情况下,我只使用接口层次结构或抽象类,基于方法签名的位置/共享实现细节的位置。

答案 4 :(得分:0)

我认为策略模式是您的最佳选择:

http://java.dzone.com/articles/design-patterns-strategy