javaでutil.Observable実現Observerモード

2135 ワード

Observerモードは主に観察者と被観察者の関係観察者が羊であり、被観察者が狼の真似をするシーンが狼が羊を呼ぶ走るコードは以下の通りである:1.被観察者類[java]view plain copy package test.pattern.observer;
import java.util.Observable;
public class Wolf extends Observable{
private String name;  


Wolf(String name) {  
    this.name = name;  
}  

public void cry(String state){  
    System.out.println(this.getName()+ " crying ");  
    this.setChanged();  
    this.notifyObservers(state);  
}  


public String getName() {  
    return name;  
}  


public void setName(String name) {  
    this.name = name;  
}  

}
2.観察者類[java]view plain copy package test.pattern.observer;
import java.util.Observable; import java.util.Observer;
public class Sheep implements Observer {
private String state = "eating";  
private String name;  

public Sheep(String name){  
    this.name = name;  
}  

public void update(Observable o, Object arg) {  
    // TODO Auto-generated method stub  
    Wolf wolf = (Wolf)o;  
    System.out.println(wolf.getName()+" crying and "+arg+" "+this.getName()+" running.....");  
    setState("running");  
}  


public String getState() {  
    return state;  
}  


public void setState(String state) {  
    this.state = state;  
}  


public String getName() {  
    return name;  
}  


public void setName(String name) {  
    this.name = name;  
}  

}
3.テスト[java]view plain copy package test.pattern.observer;
public class TestObserver {
public static void main(String[] args) {  
    Wolf wolf = new Wolf("wolf1");  
    Sheep sheep1 = new Sheep("sheep1");  
    Sheep sheep2 = new Sheep("sheep2");  
    Sheep sheep3 = new Sheep("sheep3");  
    //     ,sheep1,sheep2  ,sheep3     
    wolf.addObserver(sheep1);  
    wolf.addObserver(sheep2);  
    String wolfStat = "hungry";  
    //wolf begin cry  
    wolf.cry(wolfStat);  
}  

}
4.結果:wolf 1 crying wolf 1 crying and hungry sheep 2 running.....wolf1 crying and hungry sheep1 running…..