OOP:无法通知层次结构中的其他对象

发布于 2024-08-13 19:23:21 字数 432 浏览 11 评论 0原文

我总是很难在对象之间发送消息。考虑测验对象的层次结构:

  • 测验
    • 问题列表
      • 问题
        • 答案列表
          • 回答

如下:
测验有一个问题列表
一个问题列表有多个问题
问题有答案列表
答案列表有多个答案

单击答案时(我们这里讨论的是 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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里兽 2024-08-20 19:23:21

是的,您不应该为子对象提供指向其父对象的链接。我猜你上面解释的情况是显示层次结构。在这种情况下,您可以使用事件系统做得更好。您可以创建自定义事件,当事情发生时,父级会向事件添加侦听器来处理这些事件。

例如,您的结构的可能事件场景如下:

  • 单击“应答”(按钮),并且监听的 AnswerList 注意到这一点。
  • AnswerList 调度一个“已回答”事件,该事件由问题接收。
  • 问题调度“已回答”事件以通知问题列表将此问题标记为已回答
  • 当问题列表收到所有问题的已回答事件时,它会调度“已完成”事件以告诉测验已完成

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:

  • Answer (a button) gets clicked, and the listening AnswerList notices that.
  • The AnswerList dispatches a "answered" event, which is received by the question.
  • The Question dispatches a "answered" event to notify the Question List to mark this question as answered
  • When the Question List has received answered events by all questions, it dispatches a "finished" event to tell the Quiz that it is completed
深爱成瘾 2024-08-20 19:23:21

您可以查看 观察者 模式。在此设计模式中,对象可以侦听对象的更改(或事件)。这样,消息就可以在孩子们不直接认识他们的父母的情况下冒泡。他们只知道必须通知听众某些事情发生了变化。如果需要,您甚至可以让多个对象监听答案。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文