You are on page 1of 1

278 Implementing Associations

14.1.4 Implementing a Unidirectional Association


Implementing a unidirectional association is pretty straightforward. You have a
field in the class that is the source of the single mapping, and this field contains a
reference to the target object. The accessor returns the reference and the modifier
changes the reference.

14.1.5 Bidirectional Implementation by Pointers in


Both Directions
In this implementation the association is implemented by pointers from both
participating classes. If a mapping is single-valued, then there is a simple pointer
from one object to another, such as the pointer from Peter to NASA shown in
Figure 14.2. If a mapping is multivalued, then the object will have a set of pointers
to the other objects (for example, in Figure 14.2 NASA points to a set of pointers
that contains pointers to Peter, Jasper, and Paul). For languages that support
containment, it may be useful to contain the set of pointers rather than to point to
it. There may be space implications, however, since sets are able to grow at will.
Similarly if a single-valued mapping points to a built-in data type or to another
fundamental type, then containment can be used instead of a pointer.

Figure 14.2 Implementing by pointers in both directions.

The accessor operations are relatively straightforward. For a single-valued


mapping the accessor merely returns the reference. For a multivalued mapping
the accessor returns a set of references; however, it must not return the set of
references because the user of the set would then be able to change its
membership and break the encapsulation. The encapsulation boundary should
include all sets implementing multivalued mappings. One way out of this is to
return a copy of the set so if any alterations are made, they do not

DLKING独家制作, 欢迎访问我们的网站: www.dlking.com

You might also like