Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Associations

 

An association is an ordered pair of objects. The first element of the pair is called the key ; the second element is the value  associated with the given key.

Associations are useful for storing information in a database  for later retrieval. For example, a database can be viewed as a container that holds key-and-value pairs. The information associated with a given key is retrieved from the database by searching the database for an the ordered pair in which the key matches the given key.

Program gif introduces the Association class. The Association class concrete extension of the ComparableObject class given in Program gif.

   program4879
Program: Association fields.

An association has two fields, key and value. The key field is any object that implements the IComparable interface. The value field is any, arbitrary object.

Two constructors and two properties are defined in Program gif. The first constructor takes two arguments and initializes the key and value fields accordingly. The second constructor takes only one argument which is used to initialize the key field--the value field is set to null.

   program4896
Program: Association constructors.

The Key and the Value property each provides a get accessor. The former returns the value of the key field; the latter, returns the value of the value field.

The remaining methods of the Association class are defined in Program gif. The CompareTo method is used to compare associations. Its argument is an object that is assumed to be an instance of the Association class. The CompareTo method is one place where an association distinguishes between the key and the value. In this case, the result of the comparison is based solely on the keys of the two associations--the values have no role in the comparison.

   program4918
Program: Association methods.

Program gif also defines a ToString method. The purpose of the ToString method is to return a textual representation of the association. In this case, the implementation is trivial and needs no further explanation.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.