すべてのプレイヤーはクラブを持っているため、クラブ クラスのプレイヤーのリストを保持します。これにより、特定のクラブのすべてのプレーヤーをすばやく簡単に列挙または検索できます。ただし、その親 Club を指す Player クラスにも参照を持たない理由はありません。各方向にリンクを持つ有効な使用例があるため、両方を行います。
各プレイヤーは 1 つのクラブにしか所属できないと想定しています。そうでない場合、事態はもう少し複雑になります。
C# での例: (コンパイル/テストされていないため、軽微なエラーが含まれている可能性があります)
public class Club
{
// other class members
// this is private so that code must use Club's methods to get at the Players
private List<Player> _players;
public int PlayerCount
{
get
{
return _players == null ? 0 : _players.Count;
}
}
public void AddPlayer(Player p)
{
// null checking etc
// here you could enforce a rule that p.ParentClub must be null
// to prevent a Player from being in multiple Clubs
p.ParentClub = this;
_players.Add(p);
}
public void RemovePlayer(Player p)
{
// null checking etc
_players.Remove(p);
p.ParentClub = null;
}
}
public class Player
{
// other class members
public Club ParentClub
{ get; set; }
}
これで、次のようなことができます。
// add Player Joe to the London Club if it is not full (10 members max)
// otherwise add Joe to the Munich Club
if(londonClub.PlayerCount <= 10)
{
londonClub.AddPlayer(joePlayer);
}
else
{
munichClub.AddPlayer(joePlayer);
}
// print how many players are in the club that Joe is in
Console.WriteLine("Number of Players in Joe's Club: " + joePlayer.ParentClub.PlayerCount.ToString());
// move Joe to the Amsterdam club. Note that it does not matter what Club Joe was already in
joePlayer.ParentClub.RemovePlayer(joePlayer);
amsterdamClub.AddPlayer(joePlayer);