低耦合、紧内聚
当然这要视情况而定。但是,当较低级别的对象或系统与较高级别的系统通信时,是否应该首选回调或事件而不是保留指向较高级别对象的指针?
例如,如果我们正在开发一款游戏,我们有一个 world class
,它有一个成员变量 vector
怪物类
要与世界类
通信时,我应该更喜欢使用回调函数,还是应该在怪物类中拥有一个指向世界类的指针?
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 world class inside the monster class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您提到的原因,通常最好使用回调与更高级别的类进行通信,并避免相互/循环依赖。
就您而言,您仍然必须定义什么是较低级别的模块。世界真的需要知道怪物是什么吗?怪物不就是生物或者对手吗?怪物活动不需要某种环境吗?只有您可以回答这个问题才能找到可行的解决方案。
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.