Let suppose we have 2 classes, Pilot and Plane, being in an optional one-to-one relationship. So a Plane might have a pilot when it's flying, but when it's standing in its hangar, it has none. Similar for the Pilot.It would be just logical to hold a pointer to the Plane in the Pilot and a pointer to the Pilot in the Plane, accessible via getters and setters.Constructing the setters so that a call on any of them establishes the bidirectional relationship is surprisingly hard. I was even more surprised that I couldn't find a suitable solution on the web as this construct seems to be common to me.Does anyone know of concepts that would encapsulate such a relationship inside a class? Or an idiom to stick with normal getters/setters and still establish the relationship with one setPilot/setPlane call?
Pattern to safely establish a one to one bidirectional relationship
relationships
Let's assume that this will always be 1-1 (e.g., you wont get 2 pilots from a plane to represent pilot and co-pilot). Instead of trying to build this relationship into the Plane or Pilot classes, use a third class that provides the mapping. For lack of a better name, let's call it PilotPlaneMap here. This class could have the following public functions:class PilotPlaneMap{public void RelatePilotAndPlane(Pilot pilot, Plane plane){..} //make the relationship herepublic Pilot GetPilot(Plane plane){..} //retrieve the pilot related to given planepublic Plane GetPlane(Pilot pilot){..} //retrieve the plane related to given pilot}Not sure what language you are using, but internally you would make use of some hashmap to store the relationships. Two dictionaries could be used. One that maps Pilot->Plane, and the other maps Plane->Pilot. These are both set when calling RelatePilotAndPlane(). That's just one option.