I'm bored tonight. I saw the art of Java, so I met observer. I used this class before, but I forgot the specific usage.
, Write down this article for future use.
The following is an example. First, let us clarify the background of the example. The participants of a group meeting should be notified. If the meeting time changes, all participants should be notified in a timely manner.
To implement the observer mode, we must first understand two concepts: observer and observer. In this example, the former is the meeting personnel, and the latter is the liaison officer who specifically notifies the meeting.
First, the meeting personnel must implement an interface to receive notifications:
Meeting personnel
Class person implements observer {
String name;
Int changetimes = 0; // records the number of changes that I have seen
/**
*
*/
Public Person (string name ){
This. Name = Name;
}
/*
* I saw the notification.
*
* @ See java. util. Observer # Update (Java. util. observable, java. Lang. Object)
*/
Public void update (Observable o, Object arg ){
String first =
Name + "said: I have seen the notification," + arg;
String other = name + "said: I'm taking the test !, N times, N> = "+ changeTimes + arg;
System. out. println (changeTimes = 0? First: other );
ChangeTimes ++;
}
}
Meeting notification staff:
Class NoticeOfficer extends Observable {
/**
*
*/
Public NoticeOfficer (String content ){
This. content = content;
}
// Important notifications
String content;
Void sendnotice (list p ){
Iterator iter = P. iterator ();
While (ITER. hasnext ()){
Object o = (object) ITER. Next ();
Addobserver (observer) O );
}
Setchanged ();
Yyobservers (content );
}
}
Test class:
Public class test {
Public static void main (string [] ARGs ){
Noticeofficer officer = new noticeofficer ("There will be a meeting at 2: 60 this afternoon! ");
List personlist = new arraylist ();
Personlist. Add (new person ("principal "));
Personlist. Add (new person ("rogue "));
Personlist. Add (new person ("programmer "));
Personlist. Add (new person ("crazy "));
Officer. sendnotice (personlist );
For (INT I = 0; I <10000000; I ++ ){
}
Officer. content = "Change meeting ";
Officer. sendNotice (personList );
}
}