Java:应用Observer接口实践Observer模式
本文出自“子 孑” 博客,原文链接:http://zhangjunhd.blog.51cto.com/113473/68949
在Java中通过Observable类和Observer接口实现了观察者模式。Observer对象是观察者,Observable对象是被观察者。
void addObserver(Observer o)
setChanged();
notifyObservers();
只有在setChange()被调用后,notifyObservers()才会去调用update()。setChange()方法用来设置一个内部标志位注明数据发生了变化;notifyObservers()方法会去调用观察者对象列表中所有的Observer的update()方法,通知它们数据发生了变化。
void update(Observable o, Object arg)
2.实例一形参Object arg,对应一个由notifyObservers(Object arg);传递来的参数,当执行的是notifyObservers();时,arg为null。
package com.zj.observer; import java.util.Observable; public class NumObservable extends Observable { private int data = 0; public int getData() { return data; } public void setData(int i) { data = i; setChanged(); notifyObservers(); } }
NumObserver是观察者。当它的被观察者(NumObserable)执行了notifyObservers()后,它会执行uodate()方法。
package com.zj.observer; import java.util.Observable; import java.util.Observer; public class NumObserver implements Observer{ public void update(Observable o, Object arg) { NumObservable myObserable=(NumObservable) o; System.out.println("Data has changed to " +myObserable.getData()); } }
测试类SingleTest,在这里将观察者加入到被观察者的观察列表中。
package com.zj.observer; public class SingleTest { public static void main(String[] args) { NumObservable number = new NumObservable(); number.addObserver(new NumObserver()); number.setData(1); number.setData(2); number.setData(3); } }
结果:
Data has changed to 1
package com.zj.observers; import java.util.Observable; public class NumsObservable extends Observable { public final static Integer ODD = 1; public final static Integer EVEN = 2; private int data = 0; public int getData() { return data; } public void setData(int i) { data = i; Integer flag = EVEN; if ((data & 0x0001) == 1) flag = ODD; setChanged(); notifyObservers(flag); } }
奇数观察者OddObserver.java
package com.zj.observers; import java.util.Observable; import java.util.Observer; public class OddObserver implements Observer { public void update(Observable o, Object arg) { if (arg == NumsObservable.ODD) { NumsObservable myObserable = (NumsObservable) o; System.out.println("OddObserver:Data has changed to " + myObserable.getData()); } } }
偶数观察者EvenObserver.java
package com.zj.observers; import java.util.Observable; import java.util.Observer; public class EvenObserver implements Observer { public void update(Observable o, Object arg) { if (arg == NumsObservable.EVEN) { NumsObservable myObserable = (NumsObservable) o; System.out.println("EvenObserver:Data has changed to " + myObserable.getData()); } } }
测试类MultiTest.java
package com.zj.observers; public class MultiTest { public static void main(String[] args) { NumsObservable number = new NumsObservable(); number.addObserver(new OddObserver()); number.addObserver(new EvenObserver()); number.setData(1); number.setData(2); number.setData(3); } }
OddObserver:Data has changed to 1结果:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。