import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class PropertyChangeSupportTest {
static TestBean testBean = new TestBean();
public static void main(String[] args) {
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(testBean);
propertyChangeSupport.addPropertyChangeListener(new PropertyChangeListener(){
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("name")){
System.out.println("bean:" + PropertyChangeSupportTest.this.testBean + " field:" + evt.getPropertyName() + " value change,old value:" + evt.getOldValue() + " new value:" + evt.getNewValue());
}
}
});
testBean.setId(111);
testBean.setName("mike");
propertyChangeSupport.firePropertyChange("name","","mike"); //通知该属性值做了修改,通知相关listener进行处理
}
public static class TestBean{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
这是观察者模式的jdk应用场景,在我们平常的项目中,比如为了做到应用配置的动态加载,我们在应用启动后动态修改应用的一些配置参数时,需要通知相关应用了这个参数的应用点做出相应的变化,那么就可以用这个PropertyChangeSupport来完成。