java PropertyChangeListener

 PropertyChangeLinstener可以监听属性bean值的改变,应用Observe模式,进行一些操作

 

下面是其简单的使用过程:

1.所要监听的bean的基类:

 

package dirk.prohange;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class PropertyChangeSupportTest {

    transient protected PropertyChangeSupport listeners = new PropertyChangeSupport( this );

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        listeners.addPropertyChangeListener(listener);
    }

    protected void firePropertyChange(String prop, Object old, Object newValue) {
        listeners.firePropertyChange(prop, old, newValue);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        listeners.removePropertyChangeListener(l);
    }
}

2. 继承基类所实现的具体bean,在set方法中设置属性监听器的触发fire方法:

 

package dirk.prohange;

public class BeanTest extends PropertyChangeSupportTest {

    public static final String TEST = "test";

    private String name = "";

    public void setName(String name) {
        if (this.name.equals(name)) {
            System.out.println("BeanTest 的 name 属性没有变化!");
            return;
        }
        String oldName = this.name;
        this.name = name;
        firePropertyChange(TEST, oldName, name);
    }

    public String getName() {
        return this.name;
    }
}

 自定义监听器:

 

package dirk.prohange;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class BeanTestListener implements PropertyChangeListener {

	public void propertyChange(PropertyChangeEvent evt) {
		// TODO Auto-generated method stub
		if(evt.getPropertyName().equals(BeanTest.TEST))
			System.out.println("I need do something, what is the something");
	}
	
	public static void main(String[] args)
	{
		BeanTest test = new BeanTest();
		test.addPropertyChangeListener(new BeanTestListener());
		test.setName("dirk.zhang");
		test.setName("dirk.zhangzhang");
		System.out.println(test.getName());
	}
	

}
 

 

你可能感兴趣的:(java,属性监听)