3 回答
TA贡献1831条经验 获得超4个赞
如果您的PhaseOne//类都实现了相同的接口(比方说PhaseTwo),并且在接口上定义了方法,您可以执行以下操作:PhaseThreePhaseperformPhase
final Phase targetPhase;
switch(phase) {
case "1": targetPhase = myInstanceOfPhaseOne; break;
case "2": targetPhase = myInstanceOfPhaseTwo; break;
case "3": targetPhase = myInstanceOfPhaseThree; break;
default: throw new IllegalStateException("Unrecognised phase "+phase);
}
targetPhase.performPhase(inputParser.getSource(), inputParser.getTarget()));
TA贡献1829条经验 获得超7个赞
另一种选择是为每个阶段创建一个类和一个 IPhase 接口供他们实现。List<IPhase>使用所有不同的 Phase 实例创建一个。运行一个循环,如果 id 匹配,则执行覆盖的方法。
public interface IPhase {
public void performPhase();
public String getId();
}
for (IPhase phase : phasesList){
if (phase.equals(phase.getId())){
phase.performPhase();
// either break or continue the loop
}
}
TA贡献1811条经验 获得超5个赞
我认为,您所链接问题的公认答案非常适合您。在地图中存储对函数的引用:
Map<String,BiConsumer<T,U>> map = new HashMap<>();
map.put("1",PhaseOne::performPhase);
map.put("2",PhaseTwo::performPhase);
map.put("3",PhaseThree::performPhase);
map.get(phase).accept(inputParser.getSource(), inputParser.getTarget());
将and替换为TandU的类型。inputParser.getSource()inputParser.getTarget()
使用这种方法,Phase…类不需要公共的超类或接口。
添加回答
举报
