wg1*_*sic 5 java if-statement switch-statement
我有我想要的问题,需要摆脱一些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());
}
Run Code Online (Sandbox Code Playgroud)
这三个类WeekThreshold,MonthThreshold并YearThreshold从AbstractThreshold他们从日历中获取日期的类延伸,但这并不重要.方法quarterThreshold()很特别,可以留在那里.但是,我怎样才能摆脱那个if else块并有一个语句来调用不同的类?
编辑:忘记提及,需要调用的类来自各种数组ar[].如果数组ar[4]是月份,则MonthThreshold必须调用等.
这里可以很好的利用FactoryPattern
class ThresholdFactory
{
public static AbstractThreshold getThreshold(String criteria)
{
if ( criteria.equals("week") )
return new WeekThreshold();
if ( criteria.equals("month") )
return new MonthThreshold();
if ( criteria.equals("year") )
return new YearThreshold();
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
其余代码如下所示:
AbstractThreshold at = ThresholdFactory.getThreshold(ar[4]);
if(at != null){
firstTime = unparsedDate.format(at.getStartDate().getTime());
secondTime = unparsedDate.format(at.getEndDate().getTime());
} else {
quarterThreshold();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
626 次 |
| 最近记录: |