When the product name and price in the online store change, the member must be notified automatically. Java API provides
The observer interface and the observable class implement the so-called observer mode.
The observable class allows other objects to be notified (implemented interface observer, observer) when changes occur ).
The following is an observer (product class ):
Import java. util .*;
Public class product extends observable {
Private string name; // Product Name
Private float price; // price
Public String getname () {return name ;}
Public void setname (string name ){
This. Name = Name;
//// Set the Change Point
Setchanged ();
Yyobservers (name); // notify the observer
}
Public float getprice () {return price ;}
Public void setprice (float price ){
This. Price = price;
//// Set the Change Point
Setchanged ();
Notifyobservers (new float (price ));
}
//// The following commands can be used to update and insert a database.
Public void savetodb (){
System. Out. println ("savetodb ");
}
}
The following are two observers:
Import java. util .*;
Public class nameobserver implements observer {
Private string name = NULL;
Public void Update (observable OBJ, object Arg ){
If (ARG instanceof string ){
Name = (string) ARG;
/// The value of the product name changes to the name
System. Out. println ("nameobserver: Name changet to" + name );
}
}
}
Import java. util .*;
Public class priceobserver implements observer {
Private float price = 0;
Public void Update (observable OBJ, object Arg ){
If (ARG instanceof float ){
Price = (float) Arg). floatvalue ();
System. Out. println ("priceobserver: price changet to" + price );
}
}
}
Below are the test classes:
Public class test {
Public static void main (string ARGs []) {
Product = new product ();
Nameobserver nameobs = new nameobserver ();
Priceobserver priceobs = new priceobserver ();
/// Add the observer
Product. addobserver (nameobs );
Product. addobserver (priceobs );
Product. setname ("applet ");
Product. setprice (9.22f );
}
}
Running result:
C:/Java> JAVA Test
Nameobserver: Name changet to Applet
Priceobserver: price changet to 9.22
C:/Java>
Note: I am not liable for any of the above content from the Internet.
This post from: http://www.java3z.com/cwbwebhome/article/article1a/151.jsp? Id = 288