1

我有JComboBox很多物品。我在此组合框中添加了一个项目侦听器,用于存储所选项目:

    comboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            option = (String) e.getItem();
        }
    });

我有一个按钮,单击它时,程序会根据该选择执行任务。

按钮:

public void actionPerformed(ActionEvent e) {
  if (option.toLowerCase().compareTo("contrast stretching") == 0) { /* do sth */ } 
  else if (option.toLowerCase().compareTo("mean") == 0){ /* do sth else */ }
  // And many other else if statements

actionPerformed 函数太长了。编写代码的最佳方法是什么?我不想让单个功能太长。

4

3 回答 3

2

您可以创建一个接口(例如Task)来表示需要执行的任务。ContrastTask然后为组合框 ( , MeanTask, ...)中的每个值创建此接口的实现。最后,在您actionPerformedTask. 然后你可以运行这个任务......

Task可能看起来像这样:

public interface Task {
  [whatever result it should return] execute([whatever parameters it needs]);
}

实现可能如下所示:

public class MeanTask implements Task {
  public int execute(int a, int b) {
    return (a + b) / 2;
  }
}

您的工厂将如下所示:

private Task create(String option) {
  if (option.toLowerCase().compareTo("mean") == 0) {
    return new MeanTask();
  }
  else if ....
}

这样做的好处是每个任务的逻辑都很好地封装在自己的类中。

于 2012-08-11T08:36:59.913 回答
2

这可以帮助您:

public class Main {
  private Map<String, BaseStrategy> strategyMap = new HashMap<String, BaseStrategy>();

  {
    strategyMap.put("case1", new Strategy1());
    strategyMap.put("case2", new Strategy2());
    strategyMap.put("case3", new Strategy3());
  }

  //...

  public void actionPerformed(ActionEvent e) {
    strategyMap.get(option.toLowerCase()).processEvent();
  }

  abstract class BaseStrategy {

    public abstract void processEvent();

  }

  class Strategy1 extends BaseStrategy {

    @Override
    public void processEvent() {
      //case 1
    }
  }

  class Strategy2 extends BaseStrategy {

    @Override
    public void processEvent() {
      //case 2
    }
  }

  class Strategy3 extends BaseStrategy {

    @Override
    public void processEvent() {
      //case 3
    }
  }
}

您可以制作一个映射,其中键是定义命令的字符串,值是处理事件的策略。现在,您甚至可以将处理代码放置到其他 java 文件中,并且只需 1 行代码即可处理事件。


实际上,如果您有太多案例-Mapif-else-if-...Map 更好的方法会更快地找到适当的策略- O(ln n)而不是O(n)

于 2012-08-11T08:41:45.410 回答
0

正如 vektor 和 Eugene 发布的那样,我会将这两种解决方案结合起来:

public interface Task {
  [whatever result it should return] execute([whatever parameters it needs]);
}

//call this method in your constructor
private void initTasks() {
    this.tasks.put("option1", new Task() {
                public int execute(int a, int b) {
                   return (a + b) / 2;
                }
          });
    //init more tasks
    //this.task.put(..., ...);
}

protected Task getTask(String option) {
     return this.task(option);
}   
于 2012-08-11T09:22:55.713 回答