r/javahelp • u/thechexmo • 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.
3
u/sinistergroupon Jul 21 '20
It’s been a while since I’ve read the books but they are all related. You’re talking about the Observer Pattern where you watch or Observe state changes on an object or a system. The thing processing the changes is the listener or an observer and when you get notified of a change it’s usually using a listener with an event.
1
u/wsppan Jul 21 '20
You are studying a design pattern. You can implement it by hand, https://www.geeksforgeeks.org/observer-pattern-set-1-introduction/
Or use the built ins that come with the JDK, https://javarevisited.blogspot.com/2011/12/observer-design-pattern-java-example.html?m=1
8
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.