Search code examples
ooplanguage-agnostic

Two objects knowing of each other


I have the following problem: I'm designing a game and summing up let's say that I have three classes:

  • Player
  • PowerPlant
  • Unit

Some "use cases"

  • Player has to know how many units and powerplants he has. If the limit has been reached, more units/powerplants should not be constructed (i.e. Player has to have a reference of each element that belongs to him)
  • Units request energy from the Player, and the Player gets the energy from the PowerPlants and sends it to the Units
  • Player has to know when a Unit or a PowerPlant has been destroyed (i.e. units and PowerPlants have to be able to notify to the player that they've been destroyed)

And the only way I can get this to work, is that Player knows about PowerPlants and Units, but also each PowerPlant and Unit knows about his Player/Owner, so that they can communicate in both ways.

I somehow think that this is a code smell... when I have been in similar situations, I always have had trouble at the long term.

Thanks in advance.


Solution

  • I have had that problem in multiple occasions, and what you said is not necessarily an anti-pattern but it does add undesired complexity.

    YMMV, but in my case, I didn't really wanted to have a direct relationship between those different classes but a way to notify each other when something happens, so the cleaner way I had found was having an event manager (or any other sort of callback mechanism) to glue all logic parts together. With that tool in the belt it turned out that I could get rid of all those double references which simplified the hierarchy a lot.