Http://www.cnblogs.com/mengdd/archive/2013/02/07/2908929.html
Observer PatternObserver mode Observer
The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time.
When the subject object changes in state, all observer objects are notified, allowing them to automatically update themselves.
the composition of the Observer pattern
Abstract Theme Role : All references to observer objects are saved in a collection, and each abstract theme role can have any number of observers. Abstract topics provide an interface that can add and remove observer roles. It is generally implemented with an abstract class and interface.
Abstract Observer Role : Define an interface for all specific observers and update yourself when you get notifications for a topic.
specific topic role : Notifies all registered observers when the internal state of a specific topic changes. A specific theme role is typically implemented with a subclass.
specific Observer role : This role implements the update interfaces required by the abstract observer role in order to reconcile the state of itself with the state of the topic. Typically implemented with a subclass. If necessary, the specific observer role can save a reference to a specific topic role.
Program Examples
To illustrate the observer pattern through a program instance:
First, you define the abstract viewer:
abstract Observer Role interface watcher{ void update (String str);
It then defines the abstract subject role, the abstract observer, in which the method is declared (adding, removing observers, notifying the observer):
Abstract Theme role, watched: Observed interface watched{void void void notifywatchers (String str);
Then define the specific observer:
Implements watcher{ @Override void update (String str) {System.out.println (str); }
The following are the specific topic roles:
ImportJava.util.ArrayList;ImportJava.util.List;PublicClass concretewatchedImplementswatched{// store observer private list<watcher> List = new arraylist<watcher> (); @Override public Span style= "color: #0000ff;" >void Addwatcher (Watcher Watcher) {List.add (watcher);} @Override public void Removewatcher (Watcher Watcher) { List.remove (watcher); } @Override public void// auto-call is actually the subject of the call for
To write a test class:
Class test{void New-New new new concretewatcher (); Girl.addwatcher (Watcher1); Girl.addwatcher (WATCHER2); Girl.addwatcher (WATCHER3); Girl.notifywatchers ("Happy");}}
References
Long Zhang Teacher Java SE Series video tutorial.
Related articles on the Observer pattern in this blog:
Http://www.cnblogs.com/mengdd/archive/2012/09/08/2676587.html
Http://www.cnblogs.com/mengdd/archive/2013/01/03/2843298.html
Observer patterns and Java implementation examples