r/javahelp • • Jul 21 '20

Are there meaningful differences between Java observers, listeners and events?

I'm studying design patterns (self taught using "head first design patterns" book) and recently got into Observer patterns... The book says some things about Java out-of-the-box Observer/Observable, but it's not fully clear about what i am asking for... Maybe is a stupid question, but i want to dive deeper into this. Thanks.

20 Upvotes

8 comments sorted by

View all comments

3

u/morhp Professional Developer Jul 22 '20

It's the same concept, but there can be minor differences.

Observers usually observe changes of some value or state. Listeners don't necessarily need to listen for a state change (although there are change listeners), you can also listen to stateless events such as a button click. You probably wouldn't say you create an mouse observer (although you're still using the observer pattern), you'd call that a mouse listener.

And when you're talking about events you usually mean event objects that store some detail about a specific event, for example a mouse click event stores the object that's clicked on, the mouse position, the mouse button that was used and so on.

Observers for value changes often don't generate these details.

1

u/thechexmo Jul 22 '20

At this point, it seems like listeners are kind of headless observers. Doesn't it?

2

u/morhp Professional Developer Jul 22 '20

Not sure what you mean with "headless". Observables are a special kind of objects you can attach listeners/observers to. They're often much simpler than other classes with listeners (a button ina GUI for example), for example you could have an ObservableString class, that has a internal String field and that generates a change notification (= a very basic change event) whenever you call the setter of the String.

1

u/thechexmo Jul 22 '20

I like the ObservableString... That's a pretty good idea for some cases...

But what i was saying about headless, is that i think observers are prepared to receive not only the notification, but both notification and information too. And in the other hand, listeners maybe are ok with the sole notification.

In practice, this may not always be this way, but I'm trying to figure out some main guidelines.