Observer is a software design pattern, that is used when some objects create events and other objects should be notified when these events occur.
The main idea is that we have two types of instances: one that produces events and one that consumes them. Events producer must have three methods:
- addObserver(Observer observer)
- removeObserver(Observer observer)
- notifyObservers(…)
The first two methods are used to add and delete observers from a collection. The third method must iterate that collection and call notify(…) method of the Observer instance.
Java has its own Observer interface and Observable class, but sometimes we don’t want to extend from a class, or we want to adjust the API, you can create your own interfaces, as I’ve done in the following example: