Using Events when the number of Child Objects is Unknown

Summary

Id: 2190.1
Type: Question Question
Current Status: Resolved

Detail

13 Dec 2003 Resolved Joe “Space Invader” Foster

There is a fairly clean way of using events when the number of child objects is unknown at design time: Use a mediator object. The parent and each child contains a reference to a mediator, which child objects call to raise events for the parent to catch.

Pseudocode:

class parent
  private children() as child
  private count as long
  private withevents m as mediator
 
  sub addone()
    if m is nothing then set m = new mediator
    set children(count) = new child
    children(count).initialize m
    count = count + 1
  end sub
 
  private sub m_oif(byval sender as child)
    ...
  end sub
end class
 
class child
  private m as mediator
 
  sub bonk()
    m.bonk me
  end sub
 
  sub initialize(byval newm as mediator)
    set m = newm
  end sub
end class
 
class mediator
  event oif(byval sender as child)
 
  sub bonk(byval sender as child)
    raiseevent oif(sender)
  end sub
end class