Say I have this setup:
public class Game
{
public static World World;
public static Camera Camera;
public static Player Player;
public Game()
{
World = new World();
Camera = new Camera();
Player = new Player();
}
}
In the camera constructor I use the world object to position the camera, however I also need to access the camera in the world constructor. I cant just use Main.Camera
because it hasn't been initialized yet. How do I solve this issue? Is there a programming pattern that I can use to avoid this circular dependency problem?
Just change the initialization order
public class Game
{
public static World World;
public static Camera Camera;
public static Player Player;
public Game()
{
Camera = new Camera();
World = new World(Camera);
Player = new Player();
}
}
If there's a mutual dependence (both depend on each other), you have a problem in your design (circular dependency anti-pattern). You'll probably need to rethink your design. Try not to make a "global object" that holds the state of everything. That's also a design anti-pattern. You need to give details (in a separate question) in order for specific tips.