Reputation: 8044
I'm using an Eclipse RCP based framework that suffers from an inefficient event model. Specifically, events emitted by controls often 'cascade'. For example, a control will emit a COLOR_CHANGED
event causing the parent composite to propagate the event to sibling controls, which in turn, decide to emit their own COLOR_CHANGED
events (in response to the original event), leading to a chain reaction of sorts. I've profiled the app raising over 100,000 events to render a simple form. Frankly, I don't understand how it's not overflowing the stack.
So, I'm looking for a technique or design pattern that prevents or reduces this kind of cascade behaviour. I've had a few ideas but this can't be a new problem; there's got to be a 'best practice' out there already for event-oriented design.
My ideas:
ValidationFailedEvent
rather than generic Event
that everybody handles (and then has to interrogate it's state to determine the event type).Thanks for taking the time to read about my problem. All advice/suggestions welcome.
EDIT: Thanks to pablosaraiva, I read about Chain-of-responsibility and now have the following idea:
isHandled
property which, if set to true, will prevent the event from propagating. This should work when the event's scope is understood but won't help if the event can not be 'handled' by a single control.Upvotes: 5
Views: 419
Reputation: 3314
I've played around with lots of different approaches to this over the years. The fundamental thing you can do to fix this is to have models only emit events if they actually change. This makes models slightly more complicated for each class in the model, but it is the only way I've managed to make this paradigm work.
For example
public void setColor(Color c)
{
setBackground(c);
notify(new ColorChangedEvent(this, c));
}
would become
public void setColour(Color c)
{
if (!getBackground().equals(c))
{
setBackground(c);
notify(new ColorChangedEvent(this, c));
}
}
The standard Observable classes in java support this with the 'setChanged()' method.
A slightly easier way of implementing this (but IMHO not as good) is to make 'notify' turn off listening until it has finished notifying. That is, notify looks like
private iAmNotifying;
public void notify(Event e)
{
if (!iAmNotifying)
{
iAmNotifying = true;
doTheActualNotification(e);
iAmNotifying = false;
}
}
But this has some significant drawbacks in terms of granularity, and I've had better success with the first approach.
Upvotes: 1