1. 程式人生 > >Java觀察者模式 : Observer / Observable

Java觀察者模式 : Observer / Observable

/**
Java觀察者模式的場景:一個女孩洗澡,被很多男孩偷看。
女孩洞察後,搜尋壞男孩,然後繼續洗澡。

三個類:Boy,Girl還有主類MainClass。
*/

/*
男孩
Boy.java
*/
import java.util.Observable;
import java.util.Observer;


public class Boy implements Observer{
 
 private String name="";
 
 public Boy(String name){
  this.name=name;
 }
 
 @Override
 public void update(Observable o, Object obj) {
  
  Girl girl=(Girl)o;
  
  System.out.println(name+" 看到 "+girl.getName()+" "+girl.getStatus());
 }
 
 
 public String getName()
 {
  return name;
 }
}

 

 


/*
女孩
Girl.java
*/
import java.util.Observable;


public class Girl extends Observable{
 private String name="";
 private String thing="";
 
 public Girl(String name){
  this.name=name;
 }
 
 public void doSomething(String thing){
  this.thing=thing;
  
  this.setChanged();  
  this.notifyObservers(thing); 
 }
 
 public String getStatus(){
  return thing;
 }
 
 public String getName(){
  return name;
 }
}

 

 

/*
主類,測試
*/
import java.util.ArrayList;
import java.util.Random;

public class MainClass {

 private Girl girl=null;
 private ArrayList<Boy> boys=new ArrayList<Boy>();
 
 public MainClass() {
  
  girl=new Girl("MM");
  
  Boy boyA=new Boy("小A");
  Boy boyB=new Boy("小B");
  Boy boyC=new Boy("小C");
  Boy boyD=new Boy("小D");
  boys.add(boyA);
  boys.add(boyB);
  boys.add(boyC);
  boys.add(boyD);
  
  girl.addObserver(boyA);
  girl.addObserver(boyB);
  girl.addObserver(boyC);
  girl.addObserver(boyD);
  
  girl.doSomething("脫衣服...");
  girl.doSomething("洗澡...");
  girl.doSomething("感覺有人偷看!?停止洗澡,穿上衣服,開始搜查...");

  girlSearchBadBoy();
  
  //搞定!繼續洗澡
  girl.doSomething("再次脫衣服...");
  girl.doSomething("再次洗澡...");
 }
 
 private void girlSearchBadBoy()
 {
  Random rand=new Random();
  
  int unluckyNumber=rand.nextInt( girl.countObservers() );
  Boy unluckyBoy=boys.get(unluckyNumber);
    
  System.out.println(unluckyBoy.getName()+" 暴露,踢出去!");
  girl.deleteObserver(unluckyBoy); 
 }

 
 public static void main(String[] args) {
  new MainClass();
 }
}