Observer is a behavioral pattern. This pattern defines a publisher-subscriber communication model between a set of objects called observers and a set of objects, the observed or subjects, on whom the observers are dependent on. Observers want to know changes in the state of the subjects. Instead of maintaining a static list of observers or interested parties in the subject, the pattern allows observers to register and unregister from subjects. Subjects notify the observers on an interesting event or change.
A simple scenario involves a customer sending a courier via courier company. The customer needs to be notified of the state of the courier. Here the courier company is holding something that the customer is interested in. The customer is the observer and the courier company is the subject.
1) Customers (Observers) need to register & un-register from the courier company notifications.
2) Courier company provides a mechanism for the customers to register, un-register and also notify them on status changes.
In Java this is accomplished via interfaces.
An Observer interface: Every observer needs to expose a mechanism with which to be notified. This is provided by the Observer interface.
An Observable interface: Every subject exposes mechanisms as mentioned in (2) above.
Sample Observer and Observable interfaces are shown below.
The Courier company implements the Observable interface as follows
The Customer implements the Observer interface which provides an entry point for notifications.
Application code using the pattern is
The advantages of using the observer pattern are
1) Subjects need not maintain a static list of interested parties.
2) Observers can subscribe and un-subscribe as needed.
3) Adding Observers does not change anything in the Subjects.
4) State change logic of Subjects do not affect Observers either.
Complete code for the project is available here.