Java 我应该使用监听器还是观察器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/744762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:58:52  来源:igfitidea点击:

Should I use a Listener or Observer?

javaswingarraylistlistenerobserver-pattern

提问by Simonw

I have a dropdown box in my GUI which shows the contents of an ArrayList in another class. New objects can be added to the ArrayList elsewhere in the GUI, so I need to know when it is updated, so I can refresh the dropdown menu. From what I can gather, my two options are to extend the ArrayList class to allow me to add my own changeListener to it, or to make the class which contains the ArrayList in question extend observable.

我的 GUI 中有一个下拉框,它显示另一个类中 ArrayList 的内容。可以将新对象添加到 GUI 中其他地方的 ArrayList,因此我需要知道它何时更新,以便刷新下拉菜单。据我所知,我的两个选项是扩展 ArrayList 类以允许我向其中添加我自己的 changeListener,或者使包含相关 ArrayList 的类扩展为可观察的。

Which would be a more appropriate solution?

哪个是更合适的解决方案?

采纳答案by Jared

The two solutions are essentially implementations of the same root design pattern (the "Observer" pattern as defined by the Gang of Four.) In the former case, you are making the ArrayList itself "observable", in the latter you are making the domain object which uses the array list "observable."

这两种解决方案本质上是相同根设计模式(四人组定义的“观察者”模式)的实现。使用数组列表“observable”的对象。

My tendency would be to do the latter: make the domain object observable. This is primarily because you may eventually have other things that could change about the domain object (for which the GUI should be updated.) If it is already observable, you're already set.

我倾向于做后者:使域对象可观察。这主要是因为您最终可能会更改域对象的其他内容(应该更新 GUI)。如果它已经是可观察的,那么您已经设置好了。

Note that you don't strictly have to extend java.util.Observable- you can implement the design pattern without doing that.

请注意,您不必严格扩展java.util.Observable- 您可以在不这样做的情况下实现设计模式。

回答by erickson

The Observableimplementation in Java is rarely used, and doesn't inter-operate well with Swing. Use an EventListenerinstead.

ObservableJava 中的实现很少使用,并且不能很好地与 Swing 互操作。改用一个EventListener

In particular, is there a reason not to extend AbstractListModelor even use DefaultListModeldirectly when managing the contents of the list "elsewhere in the GUI"? Then your combo box could use a ComboBoxModelthat delegates to the same ListModelinstance, adding its own implementation to track the selection state.

特别是,在管理“GUI 其他地方”列表的内容时,是否有理由不扩展AbstractListModel甚至DefaultListModel直接使用?然后您的组合框可以使用ComboBoxModel委托给同一个ListModel实例的 a ,添加自己的实现来跟踪选择状态。

I have in mind something like this (but I haven't test it):

我想到了这样的事情(但我还没有测试过):

final class MyComboBoxModel 
  extends AbstractListModel 
  implements ComboBoxModel 
{

  private final ListModel data;

  private volatile Object selection;

  MyComboBoxModel(ListModel data) { 
    /* 
     * Construct this object with a reference to your list, 
     * which contents are managed somewhere else in the UI.
     */
    this.data = data;
    data.addListDataListener(new ListDataListener() {
      public void contentsChanged(ListDataEvent evt) { 
        fireContentsChanged(this, evt.getIndex0(), evt.getIndex1()); 
      }
      public void intervalAdded(ListDataEvent evt) { 
        fireContentsChanged(this, evt.getIndex0(), evt.getIndex1()); 
      }
      public void intervalRemoved(ListDataEvent evt) { 
        fireContentsChanged(this, evt.getIndex0(), evt.getIndex1()); 
      }
    });
  }

  public void setSelectedItem(Object selection) { 
    this.selection = selection;
    fireContentsChanged(this, 0, data.getSize() - 1);
  }

  public Object getSelectedItem() { return selection; }

  public int getSize() { return data.getSize(); }

  public Object getElementAt(int idx) { return data.getElementAt(idx); }

}

回答by MahdeTo

Always prefer composition over extension (my reference is effective java and my personal experience). extending ArrayList is simply a promise that you will not violate any of the classes invariants. It also binds you to the specific list implementation you are extending.

总是喜欢组合而不是扩展(我的参考是有效的 java 和我的个人经验)。扩展 ArrayList 只是承诺您不会违反任何类不变量。它还将您绑定到您正在扩展的特定列表实现。

回答by RS Conley

You could switch to using a GUI design pattern. Or construct a limited implementation.

您可以切换到使用GUI 设计模式。或者构建一个有限的实现。

Create a GUI Form Interface that has a method DrawXArrayList (with X being some meaningfull name. It has a parameters of type ArrayList

创建一个 GUI 窗体接口,它有一个 DrawXArrayList 方法(X 是一些有意义的名称。它有一个 ArrayList 类型的参数

Create a new class called GUIView. It has at least two methods: UpdateXArrayList, and RegisterForm

创建一个名为 GUIView 的新类。它至少有两个方法:UpdateXArrayList 和 RegisterForm

When you initialize your application have the GUI Form register itself with the class implementing GUIView. Make the class implementing GUIView visible to the form.

当您初始化您的应用程序时,让 GUI 表单向实现 GUIView 的类注册自己。使实现 GUIView 的类对表单可见。

When anything in your GUI Form updates the arraylist have it call UpdateXArrayList as the last thing it does. The UpdateXArrayList method in the class implementing GUIView will then in turn call DrawXArrayList passing the updated arraylist. DrawXArrayList in the form class implementing the GUIFormInterface will then take the steps need to update the control displaying the ArrayList.

当您的 GUI 表单中的任何内容更新时,arraylist 会调用 UpdateXArrayList 作为它所做的最后一件事。实现 GUIView 的类中的 UpdateXArrayList 方法然后将调用 DrawXArrayList 传递更新的数组列表。实现 GUIFormInterface 的窗体类中的 DrawXArrayList 然后将采取需要更新显示 ArrayList 的控件的步骤。

While this seems like a lot of steps compared to a observer and listener setup. You have more control over how the various user actions effect the UI then the observer-listener pattern. In addition you documented, in code, the interaction between the user action and the updates to the UI.

虽然与观察者和侦听器设置相比,这似乎需要很多步骤。与观察者-侦听器模式相比,您可以更好地控制各种用户操作如何影响 UI。此外,您在代码中记录了用户操作与 UI 更新之间的交互。

回答by James Schek

Why not use bindings?

为什么不使用绑定?

http://wiki.eclipse.org/index.php/JFace_Data_Binding

http://wiki.eclipse.org/index.php/JFace_Data_Binding

Bind your GUI widget to your List. Changes will propogate between the two objects transparently. Be sure to wrap your model with an appropriate observable, such as WritableList (if using the ArrayList directly).

将您的 GUI 小部件绑定到您的列表。更改将在两个对象之间透明地传播。确保使用适当的 observable 包装您的模型,例如 WritableList(如果直接使用 ArrayList)。

回答by l_39217_l

If you can add a new jar to the application, check out glazed Lists

如果您可以向应用程序添加新 jar,请查看 上釉列表