How to refactor two classes that need visibility of each other?
I have two classes,
InputManager
and DisplayManager
. In my current model, InputManager
sometimes needs to write to the display, and DisplayManager
needs to see the current state of input, so they have need of each other.
At the moment I'm handling it like:
So both objects have a reference to each other and can call each's relevant public methods. The problem is of course that I get lots of "potentially null" warnings because I can't (seemingly) pass the displayManager
via inputManager
's constructor because it doesn't exist yet, and vice versa.
I was wondering what the right approach is where I can guarantee non-null references but still have the two have access to each other?3 Replies
either have the input manager handle all the display things
or the display manager handle reading the input
or a third class that kind of wires both
hard to say without more details
If you only have one instance of each, you can:
- make them singleton directly
- use Dependency Injection and register these managers as singletons
I recommend the second option.
that would still have a cyclic dependency no?