Say I have a "MainWindow" instance that creates a "Scorekeeper" instance and many "Player" instances. If I want the Player instances to be able to address the Scorekeeper instance, the way I do it now is instantiate the Scorekeeper in the MainWindow, then when I create a Player I pass the EDIT: MainWindow /EDIT as a parameter to the Player constructor. Then I address the Scorekeeper from the Player as like "myMainWindow.myScorekeeper"
This works fine but seems a little wonky to me. Any suggestions? [ November 20, 2008: Message edited by: Bill Parsh ]
Sounds like you're passing the window to the player, not the scorekeeper; otherwise in player you'd just use "myscorekeeper" or something, right?
But in any case, that's basically the right way to do things: either provide player with what it needs as constructor arguments, and let the player store a reference for its lifetime, or alternatively, make sure all the player methods that need a scorekeeper accept one as an argument, so that the caller has to provide the scorekeeper.
A third alternative -- and one that's strongly discouraged -- is to store things in public static variables, so that the player objects can just say, for example, MainWindow.theScoreKeeper to access that static variable. The problem with this is that your code becomes terribly messy, complex, interconnected and impossible to change after a while.
Depending on the app, another thing you could do is create a singleton for the scorekeeper or mainwindow if that's applicable in this case. That way you'd be able to access it elsewhere while still preserving some of the ideal loose coupling properties.