【觀察者模式應用場景舉例】
比如在玩
【觀察者模式解釋】
類型
定義了一種一對多的依賴關系
【觀察者模式UML圖】
【觀察者模式
新建抽象發布通知父類
package carer_subject;
import java
import java
import carer_observer
public interface carer_subject_parent {
public void set_state(String state_string);
public String get_state();
public void add_observer(carer_observer carer_observer_ref);
public void sub_observer(carer_observer carer_observer_ref);
public void notityAllCarer();
}
新建發布通知實現類
package carer_subject;
import java
import java
import carer_observer
public class carer_subject_sub implements carer_subject_parent {
List<carer_observer> list_observer = new ArrayList<carer_observer>();
private String state;
public void set_state(String state_string) {
this
}
public String get_state() {
return state;
}
public void add_observer(carer_observer carer_observer_ref) {
list_observer
}
public void sub_observer(carer_observer carer_observer_ref) {
list_observer
}
public void notityAllCarer() {
state =
for (int i =
list_observer
}
}
}
新建觀察者接口
package carer_observer;
import carer_subject
public interface carer_observer {
public void show_info();
}
新建觀察者實現類
package carer_observer;
import carer_subject
public class carer_observer_imple implements carer_observer {
private carer_subject_parent carer_subject_parent_ref;
public carer_subject_parent getCarer_subject_parent_ref() {
return carer_subject_parent_ref;
}
public void setCarer_subject_parent_ref(
carer_subject_parent carer_subject_parent_ref) {
this
}
public carer_observer_imple(carer_subject_parent carer_subject_parent_ref) {
super();
this
}
public void show_info() {
System
}
}
新建客戶端運行類
package run_main;
import carer_observer
import carer_subject
import carer_subject
public class run_main {
public static void main(String[] args) {
carer_subject_parent carer_subject_parent_ref = new carer_subject_sub();
carer_observer_imple carer_observer_imple_ref
carer_subject_parent_ref);
carer_observer_imple carer_observer_imple_ref
carer_subject_parent_ref);
carer_observer_imple carer_observer_imple_ref
carer_subject_parent_ref);
carer_observer_imple carer_observer_imple_ref
carer_subject_parent_ref);
carer_subject_parent_ref
carer_subject_parent_ref
carer_subject_parent_ref
carer_subject_parent_ref
carer_subject_parent_ref
carer_subject_parent_ref
carer_subject_parent_ref
}
}
程序運行結果如下
到達終點
到達終點
到達終點
以一對多的方式進行對一方狀態的改變而去通知多方
【觀察者模式
觀察者模式observer示例代碼
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27277.html