开发者

How can I sync three classes?

开发者 https://www.devze.com 2022-12-29 17:22 出处:网络
class Foo { Bar b; List<Foo> Neighbours; } class Bar { Spam s; List<Bar> Neighbours; } class Spam { List<string> Neighbours;
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 o开发者_开发问答bjects to be in sync.

How can I do this?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消