Java Reference
In-Depth Information
continued
model, which in turn would notify all the listening views to update their states.
If this looks like a roundabout way of doing things, don't feel too bad; some
implementations prefer to pass the controller to a view's constructor, so that it
can be immediately registered and the controller can be notified immediately
after the UI is set up. Some implementations allow views to be registered with
controllers so that the controller can update their state directly, as you've seen
before. In practice, all of these approaches are fine. The key reasoning behind
the model‐view‐controller pattern is to establish a clear separation among
data, data manipulation, and data representation. In other words, never mix UI
code with data‐handling code.
Before continuing with the next pattern, you may want to read the sidebar about the so‐called
“lapsed listener” problem.
lapsed listeners
The observer pattern is a very helpful one, but it comes with a tricky issue that can
pose problems in larger applications and cause memory leaks with long‐running
applications (applications taking up more and more memory until they crash).
The problem is this: let's say that you have a large application and the user decides
to close the window of the account. The AccountWindow object is thrown away,
and the user returns to an overview screen of all accounts. (By the way, if you feel
up for it, try expanding the previous example to work with lists of accounts in a
model‐view‐controller paradigm instead of just one account. Which classes do you
need to add and which do you need to change?) So far so good, except that the win-
dow is still registered as a listener of the account object, which is still being kept
around. This prevents the garbage collector from removing the window object from
memory. In fact, the account object will just continue to notify the (hidden) win-
dow object for eternity. When an account is opened again in the UI, the program-
mer creates a new view object, so that over time, more and more objects are created
and remain stuck as listeners.
The solution is simple: make sure to deregister all listeners when it is time to
close them. Note that this is one of the few times when it makes sense to override
Object.finalize() :
@Override
public void finalize() {
// Deregister this listener
super.finalize(); // Perform rest of finalization
}
 
Search WWH ::




Custom Search