views:

165

answers:

1

I have an agent that monitors for certain conditions. For each condition, I would like to notify a different observer, because the responsibility for that condition lies with the observer.

The way to do it for a single observer/subject in C++, according to wikipedia, is to create a virtual class (similar to a Java interface), which defines the update method for the Observer, and defines the register method for the Subject. Each concrete class then inherits its respective interface.

However, I can envision this occurring for an arbitrary number of conditions, each of which would require another interface and concrete observer class for each new condition. Does kind of design make sense? Anddoes it sound reasonable to be adding an observer interface for each new condition?

+3  A: 

If you compare this to hoe Java deals with events on a GUI component (not exactly the same, but the same general idea), you wind up with something like:

public void addActionListener(ActionListener listener) { }
public void addWindowListener(WindowListener listener) { }
public void addComponentListener(ComponentListener listener) {}
public void addMouseListener(MouseListner listener) {}

all of the *Listener things are interfaces. You then provide one or more classes that implement the interfaces (I prefer one class per listener type, others prefer to make a ingle class that implements all of the listeners).

This proves to be very flexible because things can register only for the events that they are interested in.

An alternative is a single "addListener(Listener listener)" method where the Listener interface has every single possible event in it, that would be a bad idea unless you are ok with things being notified about events that they do not care about.

So, do you anticipate wanting fine grained control over what you can listen for? If so the Java model works well (works ok if you don't care about it either, it is very flexible). If you think that everything will want to be notified of all events then the single "master" way works too.

It sounds like you want fine grained control, so I'd be fine with doing it the Java event way of an interface for each general category of events.

TofuBeer
Ah, right, it's very similar to the windows event model, come to think of it.
Jack BeNimble