views:

85

answers:

2
class Foo
{
    Bar b;
    List<Foo> Neighbours;
}

class Bar
{
    Spam s;
    List<Bar> Neighbours;
}

class Spam
{
    List<string> Neighbours; 
}

Each of these classes have AddNeighbour,RemoveNeighbour methods.

User can add/remove Neighbours from any of the class at random.

I want these three objects to be in sync.

How can I do this?

+2  A: 

One approach could be to use the Observer pattern.

You could have each object register itself with the Observer, when any object changes it notifies the Observer, which then updates all other subscribers.

HTH

DannyLane
+4  A: 

Option one - Have Foo call Bar when it's updated and Bar call Spam. This will lead to tightly coupled objects and you'll probably also need to have Spam call back to Bar which calls back to Foo to sync in the other direction, yuk.

Option two - Have a class that observes each of the three objects and updates the others when one changes. (External synchroniser)

Option three - Revise the design and store the data in ONE class and implement three interfaces that return the data as either a List<Bar>, List<Foo> or List<string>. That way you can choose to store the data once (and convert as requested) or keep the object's three internal lists in sync more easily.

Option four - Have a common data model that is updated and each object observes that and syncs it's own internal list from the data model

EDIT - Following your comment that this is for three graphs, the observer pattern is probably the best way to do this. Have a single common data model that each are observing and adapting to the specific type required by the graph its serving.

Paolo
definitely would take option three or four. To make the observation of the common list a little easier you could take there a `BindingList<T>` and the observer(s) would easily be notified about any change within the underlying list.
Oliver
Thanks a lot!!!
TheMachineCharmer