q126y
q126y

Reputation: 1671

How to implement bi-directional assosiation between Classes?

I am trying to design software for video rental. I would like Movie class to have list of Actor * who acted in the movie. I would also like Actor to have list of Movie *, in which he has acted.

  1. How to ensure that there is no inconsistency between the two lists?

  2. How to initialize Movie object, whose Actor Object is not present[but will have to be created]?

Upvotes: 2

Views: 62

Answers (1)

David Osborne
David Osborne

Reputation: 6801

You can ensure consistency between the two by taking control of how the user can manage the relationships and protecting invariants. For example, ensure that an Actor's collection of Movies and a Movie's collection of Actors can only be manipulated via methods you control:

class Actor
{
   private readonly IList<Movie> movies = new List<Movies>();

   public IEnumerable Movies
   {
      get
      {
         return this.movies;
         // This could be return this.Movies.AsReadOnly() if
         // you're concerned someone might still try and cast
         // from IEnumerable
      }
   }
}

Furthermore, ensure that the owning class maintains the integrity of the relationships when either side changes:

class Actor
{
   public void AddMovie(Movie movie)
   {
      this.movies.Add(movie);

      movie.AddActor(this);
   }
}

N.B. This technique must also be replicated on the Movie class.

I don't understand what you're asking in the second part of your question.

Upvotes: 1

Related Questions