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.
Participants
Subject
Provides an interface for attaching or detaching Observers.
Concrete Subject
Object which needs to be monitored by Observers for state change.
Observer
Defines an abstract interface for updating subjects state change.
Concrete Observer
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,
public Project(String projectName) { this.projectName = projectName;
}
public void submitBid(Bid bid) {
submittedBids.add(bid); this.addObserver(bid);
}
/**
* Accept the max bid.
*/ public void acceptBid() {
int max = 0;
Bid maxBid = null;
for (int i = 0 ; i < submittedBids.size() ; i ++) { if (max < submittedBids.get(i).getAmount()) {
max = submittedBids.get(i).getAmount();
maxBid = submittedBids.get(i);
}
}
/**
* Accept max of above bids.
*/
project.acceptBid();
}
}
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.