java - 在调用类似的类 Java 时摆脱 if/else

标签 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());
}

WeekThresholdMonthThresholdYearThreshold 这三个类从 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/

相关文章:

shell - KornShell - 在 IF 语句中分组条件

python - 使用Python,如何检查 `if or` 语句中的哪个对象返回 `True` ?

java - 我可以阻止我的程序打印重复信息吗

c++ - 在 C++ 中使用 vector 设置开关

MATLAB 枚举 switch 语句总是进入第一种情况

java - 双重检查锁定是否适用于 Java 中的最终 Map?

java - 高效的编程技术

java - 如何使用 JSlider slider 或 JScrollBar 增加/减少图像的亮度

java - 从工作流步骤查找工作流实例

ios - 如何使用swift Playground 为switch语句中的随机间隔分配概率?