Java Reference
In-Depth Information
However, this is easier said than done, since a listener . . . listens. It cannot shout to
its subjects, “Hey, I'm about to get deleted; please deregister me from your lists.”
You need to make sure that this listener is deregistered when it's destroyed. A good
way to do this is to have the view send a notification to the controller (“I've been
closed, goodbye . . .”) so that the controller can proceed to deregister the listener
from the relevant views.
Another, more advanced, way of solving this issue is to work with so‐called “weak
references.” These specify a reference to an object (a listener), but allow the garbage
collector to kick in once all normal references are gone. In Java, this functionality
is provided by the WeakReference built‐in class, but it is best to explicitly program
deregistration in your code. After all, that is why removeListener methods are
provided.
Iterator Pattern
The next pattern discussed is also built in to Java itself, although contrary to the observer pattern,
the iterator pattern is much more useable.
The design goal behind an iterator is to traverse through and access a container's elements, for
instance, looping through members in a Java List object. Why is this concept so earth‐shatter-
ing, you might ask. After all, if you have a collection, it makes sense that you can loop through its
members. True, but the iterator pattern decouples the way a container is looped over from the con-
tainer. For instance, the most logical iterator for a list would loop through members by index, but
you might prefer to loop through members in reverse order, or random order, or sorted alphabeti-
cally first.
In Java, two interfaces exist to apply this pattern. Iterable is implemented by collections that can
be looped over, and they subsequently implement a method ( iterator() ) to return an object imple-
menting the Iterator interface. This is done with the methods hasNext() , next() , and remove() .
All collections in Java extend Iterable , meaning that you can get an iterator from every collection
class. The following examples illustrates how you can loop over a list using an iterator:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Bart");
list.add("Aimee");
list.add("Seppe");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
 
Search WWH ::




Custom Search