Import java. util .*;
/**
* <P>
* Example of using the observer mode.
* After your mobile phone number is changed, your friends will be notified automatically.
* </P>
*
* @ Author not attributable
* @ Version 1.0
*/
Public class observerdesignpattern extends observable {
Public observerdesignpattern (){
Super ();
// Have two friends
Addfriend (new friend ("Tom "));
Addfriend (new friend ("Jerry "));
}
Public void addfriend (friend N ){
Super. addobserver (N );
}
/**
* Mobile phone number change
* @ Param l long
*/
Public void modifyphonenumber (final long l ){
/*
* Indicates that the status has changed and the observer will not be notified if no call is made.
*/
Setchanged ();
// Notify others to change their numbers
Yyobservers (New Long (l ));
}
Class friend implements observer {
Private string name;
/**
* @ Param name: name of a friend
*/
Public friend (string name ){
This. Name = Name;
}
Public void setname (string name ){
This. Name = Name;
}
Public String getname (){
Return name;
}
Public void Update (observable o, object Arg ){
If (ARG instanceof long ){
System. Out. println (name + "you already know that your mobile phone number is changed to:" + Arg );
}
}
}
Public static void main (string [] ARGs ){
Observerdesignpattern op = new observerdesignpattern ();
// Change the mobile phone number
System. Out. println ("change my mobile phone number to 13516816888! ");
Op. modifyphonenumber (long. parselong ("13516816888 "));
}
}
/* Java. util. there are two methods in observable that are particularly important to observer. One is the setchange () method used to set an internal flag indicating that the data has changed; the other is yyobservers () the method will call the update () method of all the observer in the list to notify them that the data has changed.
Observer adds itself to this list through the addobserver () method of observable. Although this list is owned by observable, observable does not know which observers are observing and waiting for notification. The observable only provides one method for the observer to add itself to the List, and ensures that the observer will be notified of changes. Through this mechanism, multiple observers can observe the observable without affecting the implementation of the observable.
*
*
*/