Observer Pattern in Java

June 1, 2014

When it comes to programming it is quite common to hear the terms like "Event handling and listeners". This is indeed one area where Observer design pattern is extensively used.  Observer is a GoF design pattern which falls under the category of Behavioral patterns. These types of patterns describe the process of communication between objects.

Let's take look at an example where messages are saved to a database as it receives and the user is notified whenever a new message is received. Before I learned Observer pattern, the first thing which came to mind to solve this is to monitor messages using Threads and when it comes to multi-threading things get messy but this pattern involves no threading mechanism at all.

Fortunately implementing Observer pattern in Java is really easy since Java SE library provides java.util.Observable abstract class and java.util.Observer interface.

Basic Structure

The Concrete Observable class is called the Subject which is a subclass of Observable abstract class and there can be many observers which implements Observer interface observing the Subject. 


Implementation

Following implementation focuses on the example I mentioned above where when a new message is received it is inserted into a database and the user is notified.



// Database.java

// Message.java

// User.java

// Demo.java

Output:

Thank you for reading.

No comments:

Post a Comment