我有一个 friend 教我如何在 Swing 中实现 Actions。
我的想法是为应用程序的每个操作创建一个扩展 AbstractAction 的类,以便我可以在许多必须具有相同行为的组件中使用。所以我终于得到了这样的东西:
public class ActionExample extends AbstractAction {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Do something");
}
}
好吧,现在当我想使用它时,我脑子里有三个选择:
public void makeUI1() {
JButton btn = new JButton(new ActionExample("Do it"));
JMenuItem mi = new JMenuItem(new ActionExample("Do it"));
}
public void makeUI2() {
Action a = new ActionExample("Do it");
JButton btn = new JButton(a);
JMenuItem mi = new JMenuItem(a);
}
或者将其用作单例(也更改 ActionExample):
public void makeUI2() {
JButton btn = new JButton(ActionExample.getInstance());
JMenuItem mi = new JMenuItem(ActionExample.getInstance());
}
public class ActionExample extends AbstractAction {
private static final ActionExample INSTANCE = new ActionExample("Do it");
public static Action getInstance() {
return INSTANCE;
}
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Do something");
}
}
我的第一个意见是通过单例实例来实现,但我在oracle教程中看到它在将其设置到组件之前创建了一个新实例,并且在中我还看到许多代码为每个组件创建了新实例,所以我不知道什么更好以及为什么。
是否优先使用其中一种方法?
最佳答案
多实例操作允许您在操作时保存数据以供进一步使用。
假设您想要添加撤消/重做功能。您需要保存每个 Action 已经完成的 Action 。
在这种情况下,Singleton 没有提供任何优势。
关于java - 单例操作与多实例操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16446152/