views:

55

answers:

2

Hi,

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.

+1  A: 

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.

Scharrels
+2  A: 

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
poke