6

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.

1
  • To minimize the coupling, I'd make a PowerPlant hold a weak reference to a Notifyable (so the Player is Notifyable); Then, the PowerPlant can notify the player with itself etc. I think separate event manager is not strictly required.
    – comco
    Dec 15, 2013 at 22:55

1 Answer 1

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.