详解java中的PropertyChangeSupport与PropertyChangeListener

详解java中的PropertyChangeSupport与PropertyChangeListener

java中的PropertyChangeSupport与PropertyChangeListener配合使用能够实现,绑定属性会在属性值发生变化时,通知所有相关的监听器。

javaBean:

package com.wang.test.property; 
 
import java.beans.PropertyChangeListener; 
import java.beans.PropertyChangeSupport; 
 
public class TestBean { 
 
  protected final PropertyChangeSupport support = new PropertyChangeSupport(this); 
   
  private String str; 
   
  public String getStr() { 
    return str; 
  } 
 
  public void setStr(String str) { 
    support.firePropertyChange("str", this.str, str); 
    this.str = str; 
  } 
   
  public void addPropertyChangeListener(PropertyChangeListener listener) { 
    support.addPropertyChangeListener(listener); 
  } 
   
  public void removePropertyChangeListener(PropertyChangeListener listener) { 
    support.removePropertyChangeListener(listener); 
  } 
} 

 client:

package com.wang.test.property; 
 
import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 
 
public class PropertyChangeSupportTest { 
 
  public static void main(String[] args) {  
     
    TestBean test = new TestBean(); 
    test.setStr("ddddd"); 
    test.addPropertyChangeListener(new PropertyChangeListener1()); 
    test.setStr("yyyy"); 
     
    //test.addPropertyChangeListener(new PropertyChangeListener2()); 
    //test.setStr("hhhhhhf"); 
  }  
    
  public static class PropertyChangeListener1 implements PropertyChangeListener{ 
 
    @Override 
    public void propertyChange(PropertyChangeEvent evt) { 
      System.out.println( "1: " + evt.getPropertyName() + "  " + evt.getNewValue() + "  " + evt.getOldValue()); 
       
    } 
  } 
   
  public static class PropertyChangeListener2 implements PropertyChangeListener{ 
 
    @Override 
    public void propertyChange(PropertyChangeEvent evt) { 
      System.out.println( "2: " + evt.getPropertyName() + "  " + evt.getNewValue() + "  " + evt.getOldValue()); 
       
    } 
  } 
} 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

你可能感兴趣的:(详解java中的PropertyChangeSupport与PropertyChangeListener)