# Game Design: Faction/Player circular relationship

For a Java game, say I have two classes:

Player, representing a player in the game. Faction, representing a faction of players in the game.

When the game starts up, all factions are loaded into some collection and all players are loaded into some collection.

Collection<Player> players;
Collection<Faction> factions;


Say there are two variables:

Player player1;
Faction the_destroyers;


player1 is in the faction the_destroyers.

the_destroyers needs to reference player1, since player1 is in the_destroyers. At the same time, player1 needs to reference the_destroyers, for quick lookup (otherwise I would have to iterate through the collection of factions, which may be a very large collection).

Obviously, whichever variable is loaded first cannot reference the other, since the other has not yet been loaded.

Generally speaking, how do I get around this issue? Is there a simpler solution?

What I would do is make the factions be simple symbols which represent their information regardless of members (name, description etc), and keep some sort of dictionary for each match, which keeps track of which players are in which faction.

Dictionary<Faction, List<Player>>


This also allows you to do more exotic stuff like players betraying their faction and switching more easily.

For accessing the faction from the player's point of view, you can just use a field in the player's class.

void addToDictionary(Faction faction, Player player) {
player.setFaction(faction);
}


Create one type of object first without adding any references to the other.

Then you create the other type of object, and during its construction you create the bidirectional links between itself and the other object type.

The calling code would look like this:

// create players
Player player1 = new Player("1");
Player player2 = new Player("2");
Player player3 = new Player("3");

// create factions
Faction jpf = new Faction("Judean People's Front");

Faction pfj = new Faction("People's Front of Judea");

The implementation of addPlayer would then both add the player to the faction and tell the player that it is now a member of this faction:
public void addPlayer(Player player) {