1、定义被观察类,继承Observable
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 }
2、定义观察者,实现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 }
3、测试
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 }