一、定義被觀察類,繼承Observableide
1 public class Observed extends Observable{ 2 private Integer num; 3 4 public Observed() { 5 super(); 6 } 7 8 public Observed(Integer num) { 9 super(); 10 this.num = num; 11 } 12 13 public Integer getNum() { 14 return num; 15 } 16 17 public void setNum(Integer num) { 18 super.setChanged(); //設置觀察點 19 super.notifyObservers(num); //通知全部觀察者 20 this.num = num; 21 } 22 23 @Override 24 public String toString() { 25 return "Observed [num=" + num + "]"; 26 } 27 }
二、定義觀察者,實現Observer接口測試
1 public class NumberObserver implements Observer{ 2 private String name; 3 4 public NumberObserver(String name) { 5 super(); 6 this.name = name; 7 } 8 9 @Override 10 public void update(Observable o, Object arg) { 11 if(arg instanceof Integer) { 12 System.out.println(this.name + "觀察到數量更新爲:" + (Integer)arg); 13 } 14 15 } 16 17 }
三、測試this
1 public class TestObserver { 2 3 public static void main(String[] args) { 4 Observed o = new Observed(100); 5 NumberObserver no1 = new NumberObserver("A"); 6 NumberObserver no2 = new NumberObserver("B"); 7 NumberObserver no3 = new NumberObserver("C"); 8 o.addObserver(no1); 9 o.addObserver(no2); 10 o.addObserver(no3); 11 System.out.println(o); 12 o.setNum(666); 13 System.out.println(o); 14 15 } 16 }