我得到了一个基于switch语句的示例代码。我想要一些如何在arrayList或HashMap中添加它。另外,您认为哪种选择适合使用以及为什么会这样做?
public static final IFeatureExtraction create(final int piFeatureExtractionMethod, IPreprocessing poPreprocessing)
throws FeatureExtractionException
{
IFeatureExtraction oFeatureExtraction = null;
switch(piFeatureExtractionMethod)
{
case MARF.LPC:
oFeatureExtraction = new LPC(poPreprocessing);
break;
case MARF.FFT:
oFeatureExtraction = new FFT(poPreprocessing);
break;
case MARF.F0:
oFeatureExtraction = new F0(poPreprocessing);
break;
case MARF.SEGMENTATION:
oFeatureExtraction = new Segmentation(poPreprocessing);
break;
case MARF.CEPSTRAL:
oFeatureExtraction = new Cepstral(poPreprocessing);
break;
case MARF.RANDOM_FEATURE_EXTRACTION:
oFeatureExtraction = new RandomFeatureExtraction(poPreprocessing);
break;
case MARF.MIN_MAX_AMPLITUDES:
oFeatureExtraction = new MinMaxAmplitudes(poPreprocessing);
break;
case MARF.FEATURE_EXTRACTION_PLUGIN:
{
try
{
oFeatureExtraction = (IFeatureExtraction)MARF.getFeatureExtractionPluginClass().newInstance();
oFeatureExtraction.setPreprocessing(poPreprocessing);
}
catch(Exception e)
{
throw new FeatureExtractionException(e.getMessage(), e);
}
break;
}
case MARF.FEATURE_EXTRACTION_AGGREGATOR:
{
oFeatureExtraction = new FeatureExtractionAggregator(poPreprocessing);
break;
}
default:
{
throw new FeatureExtractionException
(
"Unknown feature extraction method: " + piFeatureExtractionMethod
);
}
}
return oFeatureExtraction;
}
您认为可以应用任何其他模式吗?提及您推荐的模式名称。将欣赏额外的实施想法。
答案 0 :(得分:0)
创建一个返回IFeatureExtraction实例的接口。使用Integer值作为Map的键,将该接口的实例添加到HashMap。您可以使用现有界面javax.inject.Provider
。
public interface IFeatureExtractionProvider
{
public IFeatureExtraction build(IPreprocessing poPreprocessing);
}
private final static Map<Integer, IFeatureExtractionProvider> map;
static
{
map = new HashMap<Integer, IFeatureExtractionProvider>();
map.put(MARF.LPC, new IFeatureExtractionProvider() {
@Override
public IFeatureExtraction build(IPreprocessing poPreprocessing) {
return new LPC(poPreprocessing);
}
});
// and so on...
}
public static final IFeatureExtraction create(final int piFeatureExtractionMethod, IPreprocessing poPreprocessing)
throws FeatureExtractionException
{
IFeatureExtractionProvider provider = map.get(piFeatureExtractionMethod);
if (provider == null)
throw new RuntimeException("no provider for " + piFeatureExtractionMethod);
return provider.build(poPreprocessing);
}
虽然你没有提到Spring或IoC,但你确实要求提供更多的想法......而不是在静态初始化程序中构建IFeatureExtractionProvider的Map,你可以将它与像Spring这样的IoC框架结合起来。向界面添加新方法(public int getType()
)。让您的框架将所有IFeatureExtractionProvider实例注入setter,然后根据getType()
的值将其添加到地图中。