javabean之bound属性

一个Bound属性是指当该种属性的值发生变化时,要通知其它的对象。每次属性值改变时,这种属性就点火一个PropertyChange事件(在Java程序中,事件也是一个对象)。事件中封装了属性名、属性的原值、属性变化后的新值。这种事件是传递到其它的Bean,至于接收事件的Bean应做什么动作由其自己定义。 

股价是经常变化的。

测试代码:

package com.beans;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Random;

import junit.framework.TestCase;

import static java.lang.System.out;

public class TestPropertyChange extends TestCase {

	public void testPropertyChange() {
		StockPrice stockPrice = new StockPrice();
		StockPriceListener listener = new StockPriceListener();
		stockPrice.addPropertyChangeListener(listener);
		Random random = new Random();
		for (int i = 0; i < 10; i++) {
			stockPrice.setPrice(random.nextInt(100));
		}
	}

	static class StockPrice {
		private int price;
		private PropertyChangeSupport support = new PropertyChangeSupport(this);

		public int getPrice() {
			return price;
		}

		public void setPrice(int price) {
			support.firePropertyChange("price", this.price, price);
			this.price = price;
		}

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

		public void removePropertyChangeListener(PropertyChangeListener listener) {
			support.removePropertyChangeListener(listener);
		}

	}

	static class StockPriceListener implements PropertyChangeListener {

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			out.println(evt.getOldValue() + "->" + evt.getNewValue());
		}

	}
}


你可能感兴趣的:(javabean之bound属性)