Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd recommend avoiding using the <code>Observable</code> class altogether, but rather <strong>define event-specific listeners and corresponding event definitions</strong>. Then define a list of listeners within your class along with methods to add and remove listeners, and propagate events to them (see below).</p> <p><code>Observable</code> forces you to use <code>java.lang.Object</code> to represent events and then check the event type using <code>instanceof</code>, 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 <code>Observer</code> / <code>Observable</code> altogether and used an approach similar to the below.</p> <p><strong>Event Definition</strong></p> <pre><code>public class MyChangeEvent extends EventObject { // This event definition is stateless but you could always // add other information here. public MyChangeEvent(Object source) { super(source); } } </code></pre> <p><strong>Listener Definition</strong></p> <pre><code>public interface MyChangeListener { public void changeEventReceived(MyChangeEvent evt); } </code></pre> <p><strong>Class Definition</strong></p> <pre><code>public class MyClass { // Use CopyOnWriteArrayList to avoid ConcurrentModificationExceptions if a // listener attempts to remove itself during event notification. private final CopyOnWriteArrayList&lt;MyChangeListener&gt; listeners; public class MyClass() { this.listeners = new CopyOnWriteArrayList&lt;MyChangeListener&gt;(); } 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); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload