java - Oberserve to attributes of Object with 2 Oberservers -


i got product object 2 attributes want oberserve 2 different oberservers. if change 1 attribute notification other attribute observer got changed. how can make sure notification when got changed?

import java.util.observable; public class product extends observable {          private string name;         private double price;           public void setname(string n){             name = n;             this.setchanged ();             this.notifyobservers();         }          public void setprice(double p){             price = p;             this.setchanged ();             this.notifyobservers();         }          public string getname() {             return name;          }          public double getprice() {             return price;          }     }  public class observerdemo {     public static void main(string [] args) throws exception {          product p1 = new product();         p1.addobserver((obj, arg) -> system.out.println("name changed to: " + ((product) obj).getname()+"\n"));         p1.addobserver((ob, arg) -> system.out.println("price changed to: " + ((product) ob).getprice()+"\n"));           p1.setprice(1.95);         p1.setname("milk");           p1.setname("banana");         p1.setprice(0.95);     } } 

any change on observable class notify registered observer classes. can use argument in notifyobservers method identify change , create 1 observer object.

import java.util.observable; public class product extends observable {      private string name;     private double price;       public void setname(string n){         name = n;         this.setchanged ();         this.notifyobservers("name changed " + n + "\n");     }      public void setprice(double p){         price = p;         this.setchanged ();         this.notifyobservers("price changed " + p + "\n");     }      public string getname() {         return name;      }      public double getprice() {         return price;      } }  public class observerdemo {     public static void main(string [] args) throws exception {          product p1 = new product();         p1.addobserver((obj, arg) -> system.out.println(arg));          p1.setprice(1.95);         p1.setname("milk");          p1.setname("banana");         p1.setprice(0.95);     } } 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -