Chapter 22. Events Between Java Components
A.Mahdy AbdelAziz
One of the core concepts of object orientation in Java is that every class can be considered to be a component. Components can be extended or included to form bigger components. The final application is also considered a component. Components are like Lego blocks that build up a bigger structure.
An event in Java is an action that changes the state of a component. For example, if your component is a button, then clicking on that button is an event that changes the state of the button to be clicked.
Events do not necessarily happen only on visual components. For example, you can have an event on a USB component that a device is connected. Or an event on a network component that data is transferred. Events help to decouple the dependencies between components.
Assume we have an Oven component and a Person component. These two components exist in parallel and work independently of one another. We should not make Person part of Oven, nor the other way around. To build a smart house, we want the Oven to prepare food once Person is hungry. Here are two possible implementations:
-
OvenchecksPersonin fixed, short intervals. This annoysPersonand is also expensive forOvenif we want it to check on multiple instances ofPerson. -
Personcomes with a public event,Hungry, to whichOvenis subscribed. OnceHungryis fired, ...