what is best way to model many-to-many relationship?
lets say we have a two classes , Team and Player
- any given Player can be in multiple Team s
- any Team can have as many Player s as they like
I like to call methods like
playerX.getTeamList()
to get the list of all the Team s he/she is inteamY.getPlayerList()
to get the list of all the Player s in the team
(or have some other way to do this effectively)
I can think of two ways of doing this , but they just don't feels like good oop pattens. can you think of any good ways , perhaps a design patten ?
Perfectly reasonable.
The answer from Will is correct. However, to deal with syncing, I would probably start with ObservableCollection. Have one side of the relationship be the "master" which keeps track of adds / removes on the other side and deals with syncing.
However, be aware that if one object is subscribing to events on the other that this is a strong reference that will prevent garbage collection. Most likely they will be leaving scope at the same time so this is a non-issue but it is something to be aware of.
IMHO what you describe is the "natural" way for OO. Your XXX.getXXXList() is the interface to your classes. And for a limit number of classes that would be the right way.
Consider there are 1000 classes that can be "interconnected". Than it may be interesting to have some ManyToManyManager to drop in an object, add another object to the related objects of an object and retrieve the list of all objects releated to another. That would be some sort of delegation vs. implementation.
Shure if you delegate your many-to-many to another instance your object model do not reflect that many-to-many relation anymore.
it is fine,
Player
has a collection ofTeam
andTeam
has collection ofPlayer
. You need to be careful about integrity in add/remove operations, because they are not "atomic"Relationship between players and teams form Bipartite Graph. Expecting comments(and downvotes?)! I am OOD noob.
Split the many-to-many relationship into two one-to-many's. Makes everything a lot more simple.