Observer
Observer
Simply, the Observer pattern allows one object (the observer) to watch another
(the subject). The Observer pattern allows the subject and observer to form
a publish-subscribe relationship. Through the Observer pattern, observers can
register to receive events from the subject. When the subject needs to inform its
observers of an event, it simply sends the event to each observer.
For example, you might have a spreadsheet that has an underlying data model.
Whenever the data model changes, the spreadsheet will need to update the
spreadsheet screen and an embedded graph. In this example, the subject is the
data model and the observers are the screen and graph. When the observers
receive notification that the model has changes, they can update themselves.
The benefit: it decouples the observer from the subject. The subject doesn't need
to know anything special about its observers. Instead, the subject simply allows
observers to subscribe. When the subject generates an event, it simply passes it
to each of its observers.
In the code above, the Subject interface defines the methods that a Subject must
implement in order for Observers to add and remove themselves from the Subject.
The Observer interface (above) lists the methods that an Observer must implement
so that a Subject can send an update notification to the Observer.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Iterator;
import java.util.Iterator;