我遇到了我想要并且需要摆脱一些 if else 情况的问题。我在我的项目中得到了以下代码:
if (ar[4].equals("week")) {
WeekThreshold wt = new WeekThreshold();
firstTime = unparsedDate.format(wt.getStartDate().getTime());
secondTime = unparsedDate.format(wt.getEndDate().getTime());
} else if (ar[4].equals("month")) {
MonthThreshold mt = new MonthThreshold();
firstTime = unparsedDate.format(mt.getStartDate().getTime());
secondTime = unparsedDate.format(mt.getEndDate().getTime());
} else if (ar[4].equals("quarter")) {
quarterThreshold();
} else if (ar[4].equals("year")) {
YearThreshold yt = new YearThreshold();
firstTime = unparsedDate.format(yt.getStartDate().getTime());
secondTime = unparsedDate.format(yt.getEndDate().getTime());
}
WeekThreshold
、MonthThreshold
和 YearThreshold
这三个类从 AbstractThreshold
类扩展而来,它们从日历,但这并不重要。 quarterThreshold()
方法比较特殊,可以留在那里。但是,我怎样才能摆脱 if else block 并使用一条语句来调用不同的类呢?
编辑:忘了说了,需要调用的类来自数组ar[]
。如果数组ar[4]
是月份,则必须调用MonthThreshold
等。
最佳答案
多种可能性... XYZThreshold 类是否具有通用接口(interface),如 Threshold?然后你可以用它分配一个变量,例如......
Threshold threshold = null;
if ((ar[4].equals("week")) {
threshold = new WeekThreshold();
} else ... {
}
firstTime = unparsedDate.format(threshold.getStartDate().getTime());
secondTime = unparsedDate.format(threshold.getEndDate().getTime());
这将是第一步。例如,如果您愿意,您可以使用枚举来存储您的阈值:
enum Thresholds {
WEEK("week") {
public Threshold getThreshold() {
return new WeekThreshold();
}
},
etc.
private String period;
private Thresholds(String period) {
this.period = period;
}
public abstract Threshold getThreshold();
// ...add a static class to iterate and search by period,
// ...so you can write Threshold threshold = Thresholds.getByPeriod("week").getThreshold();
}
使用枚举是个人喜好,当然,您可以对普通类做同样的事情,或者简单地将用于阈值选择的 if block 放入一个单独的类中。
关于java - 在调用类似的类 Java 时摆脱 if/else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31964885/