I have a circular dependency in my code, and I'm not sure how to resolve it.
I am developing a game. NPCs have three components that are responsible for thinking, perception, and action. These components need access to the NPC controller to access its model, but the controller needs these components to do something. Thus, both perceive each other as arguments in their constructors.
ISenseNPC sense = new DefaultSenseNPC(controller, worldQueryEngine);
IThinkNPC think = new DefaultThinkNPC(sense);
IActNPC act = new DefaultActNPC(combatEngine, sense, controller);
controller = new ControllerNPC(act, think);
(In the example above, the parameter is a bit simplified.)
Without actand think, controllernothing can be done, so I do not want to allow its initialization without them. Otherwise, this is also true. What should I do?
ControllerNPCusing thinkand actto update their state in the world:
public class ControllerNPC {
public override void Update(long tick)
{
act.UpdateFromBehavior(CurrentBehavior, tick);
CurrentBehavior = think.TransitionState(CurrentBehavior, tick);
}
}
DefaultSenseNPC controller, , -:
public class DefaultSenseNPC {
public bool IsCollidingWithTarget()
{
return worldQuery.IsColliding(controller, model.Target);
}
}