【发布时间】:2015-08-12 12:12:40
【问题描述】:
我有一个我想要并且需要摆脱一些 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()这个方法比较特殊,可以留在那里。但是,如果 else 阻塞并有一个语句来调用不同的类,我该如何摆脱它呢?
编辑:忘了提一下,需要调用的类来自各种数组ar[]。如果数组ar[4] 是月份,则必须调用MonthThreshold 等。
【问题讨论】:
-
你考虑过工厂设计模式吗?
-
这也是我的一位伙伴告诉我的,但我很新鲜,哎呀……我会用谷歌搜索,但当然任何提示都会很好:)跨度>
-
我会为你编写一些代码...给我一分钟
-
如果你想摆脱命令式代码(
if/else),你需要一个声明式解决方案;使用enum。
标签: java if-statement switch-statement