Fan
Fan

Reputation: 315

Design pattern for dependency graph

I have a program with a number of variables A, B, C..., and they have dependency relationship. For example, C's value depends on A and B's values. Whenever the value of a variable is changed, I need to update all its downstream variables. For example, if A's value is changed, I will need to recompute C's value. If C's value is changed, too, I will need to recompute the values of those variables dependent on C. Now I have code like this:

A a;
B b;
C c;

// ...

void updateC()
{
    C newC = calculateC(a, b);
    if (c != newC)
    {
        c = newC;
        updateD();
        updateE();
    }
}

As the number of variables grows this code is too difficult to maintain. There are also complex logic such as if updateD is successful then you do not need to call updateE. Is there a standard design pattern or library for such problems?

Upvotes: 1

Views: 1201

Answers (2)

Ray Tayek
Ray Tayek

Reputation: 10013

Compute the transitive closure of the graph in a matrix m. Now m(i,j) (or m(j,j)) will tell you if thing i is dependent on thing j. Multiplying this (or it's transpose) by a vector of what changed (with one's where thing j changes and zeroes elsewhere) will give you a vector of what you need to update.

Also, you would have to generate the strict partial order and sort by that.

Upvotes: 0

Essentially you need to decouple the objects A, B, C... that can be achieved using a man-in-the-middle i.e., Mediator pattern:

https://en.m.wikipedia.org/wiki/Mediator_pattern

Using the Eventbus pattern:

http://wiki.c2.com/?DataBusPattern

Using the Pub-Sub pattern:

https://en.m.wikipedia.org/wiki/Publish-subscribe_pattern

The Observer pattern:

https://en.m.wikipedia.org/wiki/Observer_pattern

And more generally Reactive Programming:

https://en.m.wikipedia.org/wiki/Reactive_programming

Upvotes: 1

Related Questions