Observer pattern comes under Behavioral design pattern.
It defines a one-to-many dependency between objects so that
when one object changes state, all its dependents are notified and updated automatically.
Behaviour & Advantages
Useful in complex event processing systems.
It decouples subject and observers so that both can be enhanced independently.
Dynamic relations can be built between subject and observer at runtime.
Provides an interface for attaching or detaching Observers.
Object which needs to be monitored by Observers for state change.
Defines an abstract interface for updating subjects state change.
An implementation of Observer which gets notified upon subjects state change.
This example shows a simple bidding system where a list of organizations compete for a project.
The system accepts the bid with highest amount.
Java provides two classes supporting Observer pattern. Class java.util.Observable acts as Subject
and Project class as Concrete Subject. Each organization can submit a bid against the project.
Interface java.util.Observer acts as Observer and Bid as Concrete Observer.
When a bid submitted by particular organization is accepted, all other other organizations gets notified.
The Project class is shown below,
* Accept max of above bids.
It gives the following output,
Mail box [MindTree] : 'MindTree' won 'Adhaar' project.
Mail box [IBM] : 'MindTree' won 'Adhaar' project.
Mail box [TCS] : 'MindTree' won 'Adhaar' project.
Mail box [Infosys] : 'MindTree' won 'Adhaar' project.