Observer/Observable and update(Observable o, Object arg)

J

Jason Cavett

So, I am currently using Observer/Observable pattern in quite a few
spots in an application I'm designing. It works great and makes
designing the entire application fairly pain-free. There's just one
question I had about part of the system that seems a
little...clunky...

When my Observable object notifies the Observer object, there are many
ways the Observer object can react depending on what changed in the
Observable object. As such, I use...

observableObject.setChanged();
observableObject.notifyObservers(SOME_STATIC_FINAL_STRING_HERE);

The Observer object then implements update(Observable o, Object arg).
Currently, I am donig an if/else comparison against the arg object so
I know exactly what to update. This seems *somewhat* clunky, though,
because some of the Observers get quite a long list of if/else's in
their update method.

Is this the right way to go about it? Is there something better I
could be doing?

Thanks
 
T

Tom Hawtin

Jason said:
So, I am currently using Observer/Observable pattern in quite a few
spots in an application I'm designing. It works great and makes
designing the entire application fairly pain-free. There's just one
question I had about part of the system that seems a
little...clunky...

The pattern is called "Observer". That doesn't mean you have to use the
interface named Observer. IMO, Observer and Observable should have been
deprecated in 1.1. The 1.1+ idiom is event listeners.
When my Observable object notifies the Observer object, there are many
ways the Observer object can react depending on what changed in the
Observable object. As such, I use...

If you use event listener, you can have one observer (the listener) with
a number of methods.

However, using listeners that try to work out what has changed is going
to be a disaster. Swing is packed full of little bugs because of this
problem, and it also has lots of hacks to prevent the problem.

The best way is to assume everything that could have led to the event
did cause it. Duplicate no state. If there is a performance problem,
optimise but don't assume that the original state + event information
gives you the current state.

You could create a log of changes (as a database does). Then when a
listener receives an event, process the entire log since last update. I
have never seen this done.

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top