11.6 When to Use References
Now that you have learned how to create a
weak listener, you can create weak key listeners, weak action
listeners, and so on. In fact, the more strong-reference loops you
can eliminate in your reference tree, the better your code will be.
However, you should be careful. Like any other powerful tool, weak
references can be dangerous if used improperly. Therefore, it is
important to know when to use them and when not to. To make this
decision, you need to know which stereotype the reference is.
References from an object can be classified into one of four
stereotypes:
- Active references
These need other objects to exist
for them to do their job. For example, your GUI panel needs the data
object before it can present it. If the data object suddenly went out
of scope, the GUI wouldn't be able to display or
modify its data. Active references should always be strong
references.
- Passive references
These are indifferent to the presence
of other objects. For example, the data objects are passive to the
GUI. If the GUI panel exists, then the data object will do it the
courtesy of informing it of its changes. However, the data object
doesn't need the GUI object to do its job. Passive
references should be weak references.
- Convenience references
These exist for the
user's convenience but are not necessarily required.
For example, in creating data cache management software such as that
used by database persistence managers, the cache is designed to
return the objects if they are in the cache and fetch them if they
aren't. In this case, keeping the objects in memory
is desirable because doing so lowers the number of expensive database
fetches that the software has to do. However, it
isn't required that these objects remain in the
cache if they are not being used. Convenience references should be
soft references.
- Dead references
With these, the object needs to be
informed after it is cleaned up. For example, a tool that needs to
keep track of the number of objects removed from the virtual machine
doesn't particularly care about the objects until
they are dead. Dead references should be phantom references.
You can create a wide variety of tools using these references.
Passive listeners in objects are only the start of the story.
References can be used to implement cache managers that centralize
storage of data in GUIs and in many other applications. They are one
of the gateways to truly advanced Java programming.
|
No comments:
Post a Comment