OOP:无法通知层次结构中的其他对象
我总是很难在对象之间发送消息。考虑测验对象的层次结构:
- 测验
- 问题列表
- 问题
- 答案列表
- 回答
- 答案列表
- 问题
- 问题列表
如下:
测验有一个问题列表
一个问题列表有多个问题
问题有答案列表
答案列表有多个答案
单击答案时(我们这里讨论的是 Flash AS3):
答案通知答案列表。
答案列表通知问题。
问题通知问题列表。
QuestionList 通知 Quiz。
换句话说,消息会冒泡。这是可能的,因为我通过每个“父”对象的“子”对象的构造函数传递该对象。但我想我在某处读到过,对象不应该知道它的父对象。我应该采取另一种方法吗?
谢谢。
I always struggle with sending messages between objects. Consider the hierarchy of objects of a quiz:
- Quiz
- QuestionList
- Question
- AnswerList
- Answer
- AnswerList
- Question
- QuestionList
So:
a Quiz has a QuestionList
a QuestionList has multiple Questions
a Question has an AnswerList
a AnswerList has multiple Answers
When an Answer gets clicked (we're talking Flash AS3 here):
Answer notifies AnswerList.
AnswerList notifies Question.
Question notifies QuestionList.
QuestionList notifies Quiz.
In other words, the message bubbles up. This is possible since I pass each 'parent' object through the constructor of it's 'child'. But I think I read somewhere that objects shouldn't be aware of it's parent. Should I take another approach?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您不应该为子对象提供指向其父对象的链接。我猜你上面解释的情况是显示层次结构。在这种情况下,您可以使用事件系统做得更好。您可以创建自定义事件,当事情发生时,父级会向事件添加侦听器来处理这些事件。
例如,您的结构的可能事件场景如下:
Yes, you shouldn't give the child objects links to their parent. I guess you the situation you explained above is a display hierarchy. In that case, you could do it much better using the event system. You can create custom events that are dispatched, when things happen and the parent would add listeners to events to take care of those.
A possible event scenario for your structure would for example be the following:
您可以查看 观察者 模式。在此设计模式中,对象可以侦听对象的更改(或事件)。这样,消息就可以在孩子们不直接认识他们的父母的情况下冒泡。他们只知道必须通知听众某些事情发生了变化。如果需要,您甚至可以让多个对象监听答案。
You might look at the Observer pattern. In this design pattern, objects can listen for changes (or events) of an object. This way, the messages can bubble up without the children knowing their parent directly. They just know that they have to notify their listeners that something has changed. You can even have multiple objects listening for answers if you want.