[英]Java design pattern for two classes sharing identical and similar but different methods
[英]What is the best design pattern in java to implement large set of methods having similar signatures?
我想在TA-Lib中实现以下类的所有cdl(烛台模式)方法。
大约有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
}
如何将参数包装在不可变的Value Object中 ?
例如
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);
创建公共数据点的最终类(类似于C中的结构),并将其作为参数传递给函数。 它有点沉重,但没有您想像的那么糟(特别是如果将该类声明为final
)。
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...
}
});
...
在这种情况下,应避免反射,因为您损失的安全性和性能不会多于输入更少的内容。
在这种情况下,我只使用基于方法签名相同/实现细节共享位置的接口层次结构或抽象类。
我认为策略模式是您的最佳选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.