观察者模式,监控变量的变化

Java使用观察者模式监控想监控的变量的变化

下面是老大类里面的一个变量变了,小弟能收到通知,并执行对应的内容

package com.lin;
import java.util.Observable;
import java.util.Observer;
import java.io.BufferedReader; 
import java.io.IOException;
import java.io.InputStreamReader; 
public class Hello {
      /**
       * @param args
       * @throws IOException
       */
      public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            System.out.print("风和日丽中\n\r");
            AxeGangBoss leader=new AxeGangBoss("老大");
            AxeGangPeople people1=new AxeGangPeople("甲");
            AxeGangPeople people2=new AxeGangPeople("乙");
            leader.addObserver(people1);
            leader.addObserver(people2);
            leader.testPeople("救命(测试小弟是否能响应通知)");
            System.out.print("阻塞等待");
      }
}
class AxeGangBoss extends Observable {
      private int intTestPeople;//定时测试小弟
      private String mName;
      public AxeGangBoss(String name) {
            // TODO Auto-generated constructor stub
            mName = name;
      }
      // 通知其他人
      public void testPeople(String msg) {
            intTestPeople=0;
            //指定变量变成特定数值时候就通知小弟
            while (intTestPeople!=100) {
                  intTestPeople+=10;
                  try {
                        Thread.sleep(200);
                  } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
            }
            //因为其他地方不会更改intTestPeople的值,
            //那就不应该在其他地方写下面这两行
            setChanged();
            notifyObservers(msg);
      }
      public String getmName() {
            return mName;
      }
      public void setmName(String mName) {
            this.mName = mName;
      }
}
class AxeGangPeople implements Observer {
      String mName;
      public AxeGangPeople(String name) {
            // TODO Auto-generated constructor stub
            mName = name;
      }
      //小弟收到信息做事
      public void update(Observable arg0, Object arg1) {
            // TODO Auto-generated method stub
            AxeGangBoss writer;
            if (arg0 instanceof AxeGangBoss) {
                  writer = (AxeGangBoss) arg0;
                  System.out.print(getmName() + "收到来自:" + writer.getmName()
                              + "的信息:" + arg1.toString()+"\n\r");
            }
      }
      public String getmName() {
            return mName;
      }
      public void setmNameString(String mName) {
            this.mName = mName;
      }
}
风和日丽中


2秒后



乙收到来自:老大的信息:救命(测试小弟是否能响应通知)
甲收到来自:老大的信息:救命(测试小弟是否能响应通知)
阻塞等待

你可能感兴趣的:(安卓)