观察者模式(蚊子咬我二)

  上一篇介绍了 监听器: 所谓的 观察者 并不是一直监听 而是通过通知方式 来传递行为,可能 对该模式理解不当 请指正
  下面总结了一下使用Obervable类和Oberser接口,还是看看源代码
package java.util;

// Referenced classes of package java.util:
//                        Observer, Vector

public class Observable {

   public Observable() {
    changed = false;
    obs = new Vector();
  }

   public synchronized void addObserver(Observer observer) {
     if (observer == null)
       throw new NullPointerException();
     if (!obs.contains(observer))
      obs.addElement(observer);
  }

   public synchronized void deleteObserver(Observer observer) {
    obs.removeElement(observer);
  }

   public void notifyObservers() {
    notifyObservers( null);
  }

   public void notifyObservers(Object obj)
        {
label0:
                {
                         synchronized( this)
                        {
                                 if(changed)
                                         break label0;
                        }
                         return;
                }
                Object aobj[];
                aobj = obs.toArray();
                clearChanged();
                observable;
                JVM INSTR monitorexit ;
                     goto _L1
                exception;
                 throw exception;
_L1:
                 for( int i = aobj.length - 1; i >= 0; i--)
                        ((Observer)aobj[i]).update( this, obj);

                 return;
        }

   public synchronized void deleteObservers() {
    obs.removeAllElements();
  }

   protected synchronized void setChanged() {
    changed = true;
  }

   protected synchronized void clearChanged() {
    changed = false;
  }

   public synchronized boolean hasChanged() {
     return changed;
  }

   public synchronized int countObservers() {
     return obs.size();
  }

   private boolean changed;
   private Vector obs;
}
接口Observer
public interface Observer {

   public abstract void update(Observable observable, Object obj);
}
和上一篇实现是一样的 方式
下面 看看使用,要模拟蚊子咬人 那么需要一个人,蚊子
人类:
/*
* 蚊子 要人的 监听器
*/
package MosquitoBiteMe2;

import java.util.Observable;
import java.util.Observer;

/*
* 四川师范大学 06级 刘毅
*/
public     class Person implements Observer {
   private String name;
         private byte count;
         public Person(String name) {
     super();
     this.name = name;
  }
   public void update(Observable o, Object arg) {
     /**
     * 判断是否是来自 蚊子的通知    
     * 判断通知的是否是我
     */
     if(Mosquito. class.isInstance(o)&&arg.hashCode()== this.hashCode()){
       /**
        * 将蚊子数加一
        */
      System.out.println(name+ ": 被蚊子咬了"+(++count)+ "下...");
    }
    
  }

}

蚊子
package MosquitoBiteMe2;

import java.util.Observable;
import java.util.Observer;

/*
* 蚊子类
*/
@SuppressWarnings(value={ "unchecked"})
public class Mosquito extends Observable{
     /**
     * 咬观察者 ob
     */    
     public void bite(Observer ob){
     this.setChanged(); //设置状态被改变
     this.notifyObservers(ob); //通知观察者ob
    }
}
测试类:
package MosquitoBiteMe2;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test1 {
   public static void main(String args[]){
     // TODO Auto-generated method stub
                 final Mosquito mos[] = new Mosquito[10]; //搞出10个蚊子来
                 final Person ps[]= new Person[5]; //搞出五个人出来
                 for( int i=0;i<mos.length;i++) mos[i]= new Mosquito();
                ps[0]= new Person( "刘毅");
                ps[1]= new Person( "吴俊");
                ps[2]= new Person( "骁勇");
                ps[3]= new Person( "何况");
                ps[4]= new Person( "萧萧");
                 /**
                 * 添加观察者
                 */
                
                   for( int j=0;j<mos.length;j++){
                     for( int i=0;i<ps.length;i++){    
                            mos[j].addObserver(ps[i]);
                    }
                     }
                 /**
                 * 启动 三个线程来模拟 蚊子咬人
                 */
                 ExecutorService exec = Executors.newFixedThreadPool(2);
                 exec.execute( new Runnable(){    
                     public void run(){
                     while( true){
                         try {
                 Thread.sleep(1000);
                                                         int m= new Random().nextInt(10); //蚊子
                                                         int p= new Random().nextInt(5); //人
                                                        mos[m].bite(ps[p]);
                                } catch(InterruptedException e) {
                         e.printStackTrace();
                    }
                     }
                    }
                 });
                exec.execute( new Runnable(){    
                   public void run(){
                     while( true){
                         try {
                 Thread.sleep(1000);
                                                     int m= new Random().nextInt(10); //蚊子
                                                     int p= new Random().nextInt(5); //人
                                                     mos[m].bite(ps[p]);
                                } catch(InterruptedException e) {
                         e.printStackTrace();
                    }
                    }
                 }
                 });
                 exec.execute( new Runnable(){    
                     public void run(){
                     while( true){
                         try {
                 Thread.sleep(1000);
                                                         int m= new Random().nextInt(10); //蚊子
                                                         int p= new Random().nextInt(5); //人
                                                        mos[m].bite(ps[p]);
                                } catch(InterruptedException e) {
                         e.printStackTrace();
                    }
                     }
                    }
                 });
                 //这里 额外添加了三个线程 但是每次 只有线程 在运行 呵呵 接触一下1.5的 线程并发库吧    
                 exec.shutdown(); //通知挂起的线程从线程池中移除
  }

}
运行结果:
萧萧: 被蚊子咬了1下...
吴俊: 被蚊子咬了1下...
何况: 被蚊子咬了2下...
何况: 被蚊子咬了1下...
萧萧: 被蚊子咬了2下...
何况: 被蚊子咬了3下...
吴俊: 被蚊子咬了2下...
萧萧: 被蚊子咬了3下...
骁勇: 被蚊子咬了1下...
吴俊: 被蚊子咬了3下...
萧萧: 被蚊子咬了4下...
吴俊: 被蚊子咬了4下...
何况: 被蚊子咬了4下...
萧萧: 被蚊子咬了5下...
吴俊: 被蚊子咬了5下...
骁勇: 被蚊子咬了2下...
骁勇: 被蚊子咬了3下...
萧萧: 被蚊子咬了6下...
何况: 被蚊子咬了5下...
骁勇: 被蚊子咬了4下...
萧萧: 被蚊子咬了7下...
骁勇: 被蚊子咬了5下...
刘毅: 被蚊子咬了1下...
萧萧: 被蚊子咬了8下...
何况: 被蚊子咬了6下...
刘毅: 被蚊子咬了2下...
何况: 被蚊子咬了7下...
萧萧: 被蚊子咬了9下...
何况: 被蚊子咬了8下...
萧萧: 被蚊子咬了10下...
刘毅: 被蚊子咬了3下...
刘毅: 被蚊子咬了3下...
刘毅: 被蚊子咬了4下...
何况: 被蚊子咬了9下...
萧萧: 被蚊子咬了11下...
萧萧: 被蚊子咬了12下...
吴俊: 被蚊子咬了6下...
刘毅: 被蚊子咬了5下...
萧萧: 被蚊子咬了13下...
骁勇: 被蚊子咬了6下...
刘毅: 被蚊子咬了6下...
吴俊: 被蚊子咬了7下...
刘毅: 被蚊子咬了7下...
萧萧: 被蚊子咬了14下...
骁勇: 被蚊子咬了7下...
萧萧: 被蚊子咬了15下...
我先前还很幸运: 没有怎么被咬 后来就惨了 还是给咬成了青红头了

你可能感兴趣的:(观察者模式,职场,休闲)