第一种方式:拉
- package com.work.pattern.observer;
- /**
- * @author wangmingjie
- * @date 2008-6-29下午07:21:38
- */
- import java.util.Observable;
- import java.util.Observer;
- public class EvenObserver implements Observer {
- public void update(Observable o, Object arg) {
- if (o instanceof NumsObservable)
- if (((NumsObservable) o).getData()%2 == 0) {
- NumsObservable myObserable = (NumsObservable) o;
- System.out.println("EvenObserver:Data has changed to "
- + myObserable.getData());
- }
- }
- }
- package com.work.pattern.observer;
- import java.util.Observable;
- /**
- * @author wangmingjie
- * @date 2008-6-29下午07:19:30
- */
- 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();//拉
- }
- // setChange()方法用来设置一个内部标志位注明数据发生了变化;notifyObservers()方法会去调用观察者对象列表中所有的Observer的update()方法,通知它们数据发生了变化。
- // 只有在setChange()被调用后,notifyObservers()才会去调用update()。
- }
测试代码如下:
public class ObserverTest {
public static void main(String[] args) {
NumsObservable number = new NumsObservable();
number.addObserver(new EvenObserver());
number.setData(1);
number.setData(2);
number.setData(3);
}
}
第二中方式是推:
- 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);//推送方式
- }
- // setChange()方法用来设置一个内部标志位注明数据发生了变化;notifyObservers()方法会去调用观察者对象列表中所有的Observer的update()方法,通知它们数据发生了变化。
- // 只有在setChange()被调用后,notifyObservers()才会去调用update()。
- }
- 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());
- }
- }
- }