How do I make a Class extend Observable when it has extended another class too?

前端 未结 6 1776
野性不改
野性不改 2020-12-13 07:48

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

However I already have it extending another class.

What should I do?

6条回答
  •  Happy的楠姐
    2020-12-13 07:56

    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).

    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.

    Event Definition

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

    Listener Definition

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

    Class Definition

    public class MyClass {
      // Use CopyOnWriteArrayList to avoid ConcurrentModificationExceptions if a
      // listener attempts to remove itself during event notification.
      private final CopyOnWriteArrayList listeners;
    
      public class MyClass() {
        this.listeners = new CopyOnWriteArrayList();
      }
    
      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);
        }
      }
    }
    

提交回复
热议问题