Posted on 2007-11-28 20:34
flustar 閱讀(648)
評論(0) 編輯 收藏 所屬分類:
Design Patterns
《設(shè)計模式》一書對Observer是這樣描述的:
定義對象間的一種一對多的依賴關(guān)系,當(dāng)一個對象的狀態(tài)發(fā)生改變時,所有依賴于它的對象都將得到通知并自動更新。
舉個例子,在現(xiàn)實生活中,父母與孩子是最親密的人。父母做為孩子(被觀察者)的監(jiān)護人(觀察者),當(dāng)孩子和別人打架后,一定會告訴他的父母這件事(呵呵,當(dāng)孩子很小時,通常會告訴父母,長大了以后,可能不會,這里的孩子指的是小孩子),當(dāng)孩子獲得獎學(xué)金后,也一定會告訴他的父母。下面我用Observer實現(xiàn)這個程序。代碼如下:
import java.util.Vector;
class Children{
static private Vector<Observer> obs;
static private String state=null;
static{
obs=new Vector<Observer>();
}
public static void attach(Observer o){
obs.addElement(o);
}
public static void detach(Observer o){
obs.removeElement(o);
}
public void setState(String str){
state=str;
}
public String getState(){
return state;
}
public void notifyObs(){
for(Observer o:obs){
o.update(this);
}
}
}
interface Observer{
public void update(Children child);
}
class Parent implements Observer{
public void update(Children child){
if(child.getState().equals("fight")){
System.out.println("Parent,他和別人打架了");
}else if(child.getState().equals("scholarship")){
System.out.println("告訴Parent,他得到了獎學(xué)金");
}
}
}
class Mother implements Observer{
public void update(Children child){
if(child.getState().equals("fight")){
System.out.println("告訴Mother,他和別人打架了");
}else if(child.getState().equals("scholarship")){
System.out.println("告訴Mother,他得到了獎學(xué)金");
}
}
}
public class Client {
public static void main(String[] args) {
Children child=new Children();
Observer parent=new Parent();
Observer mother=new Mother();
child.attach(parent);
child.attach(mother);
child.setState("fight");
child.notifyObs();
child.setState("scholarship");
child.notifyObs();
}
}
輸出如下:
告訴Parent,他和別人打架了
告訴Mother,他和別人打架了
告訴Parent,他得到了獎學(xué)金
告訴Mother,他得到了獎學(xué)金
小結(jié):對于Observer模式,觸發(fā)事件的對象-Subject對象無法預(yù)測可能需要知道該事件的所有對象。為了解決這一問題,我們創(chuàng)建一個Observer接口,要求所有的Observer負責(zé)將自己注冊到Subject上。