Of course it depends on the situation. But when a lower level object or system communicate with an higher level system, should callbacks or events be preferred to keeping a pointer to the higher level object?
For example, if we are working on a game, we have a world class
that has a member variable vector<monster> monsters
. When the monster class
is going to communicate with the world class
, should I prefer using a callback function then or should I have a pointer to the wor开发者_开发知识库ld class inside the monster class?
It generally is preferrable to use callbacks to communicate with higher level classes for the reasons you mention and to avoid mutual/cyclic dependencies.
In your case, you still have to define what is the lower level module. Should world really need to know what a monster is? Aren't monster just creatures or opponenents? Doesn't monster need some kind of environment to act in? Only you can answer that to come to a workable solution.
精彩评论