Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 538
bgusach Avatar asked Dec 15 '13 12:12

bgusach


People also ask

What two objects attract each other?

The universal law of gravitation states that every object exerts a gravitational force of attraction on every other object.

How do two objects interact with each other?

Explanation: Newton's Third Law states that when two objects interact, they produce equal and opposite forces on each other. As a result, any force exerted on one body is often counterbalanced by an equal and opposite force exerted on the interacting partner.

What happens when two objects are near with one another?

Positively charged objects and neutral objects attract each other; and negatively charged objects and neutral objects attract each other.


1 Answers

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.

like image 55
Pedrom Avatar answered Oct 14 '22 09:10

Pedrom