Java中的Observable和Observer(觀察者模式)

觀察者模式介紹

        在Java中經過Observable類和Observer接口實現了觀察者模式。一個Observer對象監視着一個Observable對象的變化,當Observable對象發生變化時,Observer獲得通知,就能夠進行相應的工做。java

        若是畫面A是顯示數據庫裏面的數據,而畫面B修改了數據庫裏面的數據,那麼這時候畫面A就要從新Load。這時候就能夠用到觀察者模式數據庫

如下例子演示Observable和Observer的使用ide

import java.util.Observable;
import java.util.Observer;

public class MainClass {

	public static void main(String[] args) {
		BeingWatch beingWatch = new BeingWatch();
		//Observable中使用vector來管理加入的Observer對象,
		//並且update從最後加入的Observer對象開始
		beingWatch.addObserver(new Watcher_1());
		beingWatch.addObserver(new Watcher_2());
		
		beingWatch.count(10);
		
		System.out.println("Final line in the main function...");
	}

}

class BeingWatch extends Observable {
	
	public void count(int num) {
		for (; num >= 0; num--) {
			setChanged();
			notifyObservers(num);
		}
	}
}

class Watcher_1 implements Observer {

	@Override
	public void update(Observable o, Object arg) {
		System.out.println("Watcher_1 count: " + arg);
	}
	
}

class Watcher_2 implements Observer {

	@Override
	public void update(Observable o, Object arg) {
		if (((Integer)arg).intValue() <= 5) {
			System.out.println("Watcher_2 count: " + arg);
		}
	}
	
}

輸出結果————spa

Watcher_1 count: 10
Watcher_1 count: 9
Watcher_1 count: 8
Watcher_1 count: 7
Watcher_1 count: 6
Watcher_2 count: 5
Watcher_1 count: 5
Watcher_2 count: 4
Watcher_1 count: 4
Watcher_2 count: 3
Watcher_1 count: 3
Watcher_2 count: 2
Watcher_1 count: 2
Watcher_2 count: 1
Watcher_1 count: 1
Watcher_2 count: 0
Watcher_1 count: 0
Final line in the main function...code

相關文章
相關標籤/搜索