Need some help with a pattern..
Hope someone can answer this one simply for me :)
If one object has a list of references to all of its child objects, and needs to know about changes to those child objects, which pattern would be best to use here?
I had thought observer, but this is defined as:
Define a one-to-many dependency between objects so that when one object changes state, all its dependants are notified and updated automatically.
And I would seem to be looking for the opposite of this. Or is it a case of setting the parent object as each childs dependant?
Cheers
[580 byte] By [
N3ila] at [2007-11-26 15:49:51]

# 5
> I had thought observer, but this is defined as:
>
> Define a one-to-many dependency between objects so
> that when one object changes state, all its
> dependants are notified and updated automatically.
>
> And I would seem to be looking for the opposite of
> this. Or is it a case of setting the parent object
> as each childs dependant?
One-to-many means: exactly one item associated to 0 or more items. 1 falls in the range of 0 to infinity.
You seem to have figured out the answer in the last sentence I quote above. Patterns aren't about semantics. Whether you call one the child and one the parent in your design is irrelevant in terms of the pattern. In the context of the pattern what you call the parent is the child and vice-versa. I've had the events going in both directions before. If you do so, just consider the possibility of inifinite cycles in the events.
A couple of other notes: Don't use the Observer class in Java. It's broken. When you add the parent as a listener on it's children, holding onto a single child anywhere in the Object graph will keep the entire object graph from being garbage collected unless you explicitly remove the listeners. Since it amounts to explicit memory management, you may want to use WeakReferences to hold the listeners. If you want to also be able to add strong listeners, add a switch and/or overloaded addListener methods.
# 6
> A couple of other notes: Don't use the Observer
> class in Java. It's broken. When you add the parent
> as a listener on it's children, holding onto a single
> child anywhere in the Object graph will keep the
> entire object graph from being garbage collected
> unless you explicitly remove the listeners. Since it
> amounts to explicit memory management, you may want
> to use WeakReferences to hold the listeners. If you
> want to also be able to add strong listeners, add a
> switch and/or overloaded addListener methods.
REALLY good point about GC and WeakReferences.
%