Usage examples: The Observer pattern is pretty common in Java code, especially in the GUI components. It provides a way to react to events happening in other objects without coupling to their classes.
Here are some examples of the pattern in core Java libraries:
Identification: The pattern can be recognized if you see a subscription method that stores incoming objects in a list. You can confirm the identification, if you see some sort of notification method that iterates over objects in that list and calls their “update” method.
Event subscription
In this example, the Observer pattern establishes indirect collaboration between objects of a text editor. Each time the Editor object changes, it notifies its subscribers. EmailNotificationListener and LogOpenListener react to these notifications by executing their primary behaviors.
Subscriber classes aren’t coupled to the editor class and can be reused in other apps if needed. The Editor class depends only on the abstract subscriber interface. This allows adding new subscriber types without changing the editor’s code.
listeners/EmailNotificationListener.java: Sends emails upon receiving notification
packagerefactoring_guru.observer.example.listeners;importjava.io.File;publicclassEmailNotificationListenerimplementsEventListener {privateString email;publicEmailNotificationListener(String email) {this.email= email; } @Overridepublicvoidupdate(String eventType,File file) {System.out.println("Email to "+ email +": Someone has performed "+ eventType +" operation with the following file: "+file.getName()); }}
listeners/LogOpenListener.java: Writes a message to a log upon receiving notification
packagerefactoring_guru.observer.example.listeners;jaimportjava.io.File;publicclassLogOpenListenerimplementsEventListener {privateFile log;publicLogOpenListener(String fileName) {this.log=newFile(fileName); } @Overridepublicvoidupdate(String eventType,File file) {System.out.println("Save to log "+ log +": Someone has performed "+ eventType +" operation with the following file: "+file.getName()); }}
Save to log \path\to\log\file.txt: Someone has performed open operation with the following file: test.txt
Email to admin@example.com: Someone has performed save operation with the following file: test.txt