I’m having a hard time understanding the DEM (Delegation Event Model) in Java. After reading this question with answers I didn’t get the explanation I needed.
What are the motivations for using DEM?
My observations in the examples I’ve seen are:
- There is a model with a list of listeners.
- That model also has a methods like
fireThisOrThat()that are called from other methods likeaddThisOrThat.
I will get this on an upcoming exam, that’s why I need to understand it and how to use it.
Delegation means a source generates an event and sends it to one or more listeners.
Java Swing is an excellent example of delegation. A Swing object, like a
JButton, will generate events. In the example of aJButton, an event would be that the button image receives a left click (the button is pressed).Any number of other objects can listen to the
JButton. This allows one or more event actions to take place as a result of theJButtonevent.Suppose you have a
JTextArea. You can have a listener on theJButtonsuch that when theJButtonfires a left mouse click event, theJTextArealistener edits the text and writes the text to a database. In other words, you push (left click) a button on the screen, and the text in aJTextAreais written to a database.By using delegation, the
JButtonand theJTextAreaaren’t coupled together. You could replace theJTextAreawith another Swing component, and the Swing components would still work together.