当扩展另一个类时,如何使类扩展Observable? [英] How do I make a Class extend Observable when it has extended another class too?

查看:129
本文介绍了当扩展另一个类时,如何使类扩展Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,我希望将我的课程变成一个可观察的课程。

I am learning Java and I want to make my class into an observable class.

但是我已经让它扩展了另一个类。

However I already have it extending another class.

我该怎么办?

推荐答案

我建议避免完全使用 Observable 类,而是定义特定于事件的侦听器和相应的事件定义。然后在类中定义一个监听器列表,以及添加和删除监听器的方法,并将事件传播给它们(见下文)。

I'd recommend avoiding using the Observable class altogether, but rather define event-specific listeners and corresponding event definitions. Then define a list of listeners within your class along with methods to add and remove listeners, and propagate events to them (see below).

可观察强制您使用 java.lang.Object 来表示事件,然后使用 instanceof ,这是一种丑陋的非OO方法,使代码更难理解。如果你看一下javax.swing包中的类,你会看到他们完全避免使用 Observer / Observable 使用类似于下面的方法。

Observable forces you to use java.lang.Object to represent events and then check the event type using instanceof, which is an ugly non-OO approach, and makes the code more difficult to understand. If you look at the classes within the javax.swing package you'll see they avoided using Observer / Observable altogether and used an approach similar to the below.

事件定义

public class MyChangeEvent extends EventObject {
  // This event definition is stateless but you could always
  // add other information here.
  public MyChangeEvent(Object source) {
    super(source);
  }
}

听众定义

public interface MyChangeListener {
  public void changeEventReceived(MyChangeEvent evt);
}

类定义

public class MyClass {
  // Use CopyOnWriteArrayList to avoid ConcurrentModificationExceptions if a
  // listener attempts to remove itself during event notification.
  private final CopyOnWriteArrayList<MyChangeListener> listeners;

  public class MyClass() {
    this.listeners = new CopyOnWriteArrayList<MyChangeListener>();
  }

  public void addMyChangeListener(MyChangeListener l) {
    this.listeners.add(l);
  }

  public void removeMyChangeListener(MyChangeListener l) {
    this.listeners.remove(l);
  }

  // Event firing method.  Called internally by other class methods.
  protected void fireChangeEvent() {
    MyChangeEvent evt = new MyChangeEvent(this);

    for (MyChangeListener l : listeners) {
      l.changeEventReceived(evt);
    }
  }
}

这篇关于当扩展另一个类时,如何使类扩展Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆