A StaticDictionary is a class which hides the update
methods of a dictionary object. This is useful if
you have an object which has an internal dictionary
and you would like to make available read-only access to that
dictionary. To do so, you could provide a public method
which return the type StaticDictionaryInterface:
private DictionaryInterface members; // or perhaps private Dictionary members
public StaticDictionaryInterface getMembers()
{ return members; }
but someone can always bypass this by checking if
a StaticDictionaryInterface is really a DictionaryInterface
and gain update access to your internal dictionary:
StaticDictionaryInterface sc = yourObject.getMembers();
if (sc instanceof DictionaryInterface)
{
DictionaryInterface c = (DictionaryInterface) sc;
// wreak havoc with your Dictionary
}
The StaticDictionary class provides an elegant way
around this by creating an object which cannot be
cast to a Dictionary or DictionaryInterface:
private DictionaryInterface members;
public StaticDictionaryInterface getMembers()
{ return new StaticDictionary(members); }
A recommended way for your to use the StaticDictionary
class is to only create it once and always return
that reference.
private StaticDictionary sc;
public StaticDictionaryInterface getMembers()
{
if (sc == null)
sc = new StaticDictionary(members);
return sc;
}
Note, however, that if you create a new members
collection, you will need to create a new StaticDictionary
object as well, since there is no way to change the DictionaryInterface
that the StaticDictionary refers to. Also, be aware that in such cases,
other object which hold references to your old StaticDictionary object
will have stale object references.
Create a StaticDictionary which provides read-only
access to a Dictionary.
Parameters:
collection - a collection. Note that the parameter type is
StaticDictionaryInterface but normally the actual
collection passed will implement DictionaryInterface
or some other interface which provides update access to the
collection.
Get the key corresponding to an item.
Note that a dictionary may contain the same
item via multiple keys. If so, this method returns
one, but the interface does not specify which one
(i.e. it does not have to be the first one entered
in the dictionary, or the first one as found in
the elements() enumeration.
public void contentsChanged(com.sas.collection.ContentsChangedEvent event)
Handle a change event from the original collection.
A new ContentsChangedEvent is fired, with this dictionary
as the source (since this dictionary is what the listener
is listening to, we should not simply resend
the event, since it's getSource() method
would then reveal the identity of the actual collection
we're mirroring.)
Specified by:
contentsChanged in interface com.sas.collection.ContentsChangedListener