Java之设计模式之 Observer 观察者

阅读更多
java.util.Observer
    - 观察者。实现该接口后,能够接收到来自被观察者因改动而发出的通知。
    update() 方法,会被 Observable 调用。

java.util.Observable
    - 被观察者。
    setChanged() 方法来 设置 change 为 true
    notifyObservers() 方法向观察者发送信息。

下面的例子中,News 对象是被两个 Reader 观察。


package com.concretepage.util;
import java.util.Observable;
import java.util.Observer;
 
// First observer 
class FirstNewsReader implements Observer {
    public void update(Observable obj, Object arg) {
        System.out.println("FirstNewsReader got The news:"+(String)arg);
    }
}
 
//Second Observer
class SecondNewsReader implements Observer {
    public void update(Observable obj, Object arg) {
        System.out.println("SecondNewsReader got The news:"+(String)arg);
    }
}
 
// This is the class being observed.
class News extends Observable {
    void news() {
        String[] news = {"News 1", "News 2", "News 3"};
        for(String s: news){
            //set change
            setChanged();
            //notify observers for change
            notifyObservers(s);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Error Occurred.");
            }
        }
    }
}
 
//Run Observer and Observable
class ObserverObservableDemo {
    public static void main(String args[]) {
        News observedNews = new News();
        FirstNewsReader reader1 = new FirstNewsReader();
        SecondNewsReader reader2 = new SecondNewsReader();
        observedNews.addObserver(reader1);
        observedNews.addObserver(reader2);
        observedNews.news();
        
    }
}



/**

OUT PUT:

SecondNewsReader got The news:News 1
FirstNewsReader got The news:News 1
SecondNewsReader got The news:News 2
FirstNewsReader got The news:News 2
SecondNewsReader got The news:News 3
FirstNewsReader got The news:News 3




*/







引用请注明,
原文出处:https://lixh1986.iteye.com/blog/2442417
















-

你可能感兴趣的:(java,设计模式,Observer,观察者)