首页 > 技术文章 > 用java.util.Observable实现Observer模式

gaoyihan 2015-03-02 21:22 原文

本文转载自:dada360778512的博客

原文链接:http://blog.csdn.net/dada360778512/article/details/6977758

Observer模式  主要是观察者与被观察者之间的关系

观察者为羊,被观察者为狼  模仿的场景为狼叫羊跑

代码如下:

1.被观察者类

[java] view plaincopy
 
  1. package test.pattern.observer;  
  2.   
  3.   
  4. import java.util.Observable;  
  5.   
  6.   
  7. public class Wolf extends Observable{  
  8.       
  9.     private String name;  
  10.   
  11.   
  12.     Wolf(String name) {  
  13.         this.name = name;  
  14.     }  
  15.       
  16.     public void cry(String state){  
  17.         System.out.println(this.getName()+ " crying ");  
  18.         this.setChanged();  
  19.         this.notifyObservers(state);  
  20.     }  
  21.   
  22.   
  23.     public String getName() {  
  24.         return name;  
  25.     }  
  26.   
  27.   
  28.     public void setName(String name) {  
  29.         this.name = name;  
  30.     }  
  31.       
  32. }  


 

2.观察者类

[java] view plaincopy
 
  1. package test.pattern.observer;  
  2.   
  3.   
  4. import java.util.Observable;  
  5. import java.util.Observer;  
  6.   
  7.   
  8. public class Sheep implements Observer {  
  9.       
  10.     private String state = "eating";  
  11.     private String name;  
  12.       
  13.     public Sheep(String name){  
  14.         this.name = name;  
  15.     }  
  16.       
  17.     public void update(Observable o, Object arg) {  
  18.         // TODO Auto-generated method stub  
  19.         Wolf wolf = (Wolf)o;  
  20.         System.out.println(wolf.getName()+" crying and "+arg+" "+this.getName()+" running.....");  
  21.         setState("running");  
  22.     }  
  23.   
  24.   
  25.     public String getState() {  
  26.         return state;  
  27.     }  
  28.   
  29.   
  30.     public void setState(String state) {  
  31.         this.state = state;  
  32.     }  
  33.   
  34.   
  35.     public String getName() {  
  36.         return name;  
  37.     }  
  38.   
  39.   
  40.     public void setName(String name) {  
  41.         this.name = name;  
  42.     }  
  43.   
  44.   
  45. }  


 

3.测试

[java] view plaincopy
 
  1. package test.pattern.observer;  
  2.   
  3.   
  4.   
  5.   
  6. public class TestObserver {  
  7.   
  8.   
  9.     public static void main(String[] args) {  
  10.         Wolf wolf = new Wolf("wolf1");  
  11.         Sheep sheep1 = new Sheep("sheep1");  
  12.         Sheep sheep2 = new Sheep("sheep2");  
  13.         Sheep sheep3 = new Sheep("sheep3");  
  14.         //注册观察者,sheep1,sheep2加入,sheep3未加入  
  15.         wolf.addObserver(sheep1);  
  16.         wolf.addObserver(sheep2);  
  17.         String wolfStat = "hungry";  
  18.         //wolf begin cry  
  19.         wolf.cry(wolfStat);  
  20.     }  
  21. }  


 

4.结果:

wolf1 crying 
wolf1 crying and hungry sheep2 running.....
wolf1 crying and hungry sheep1 running.....

推荐阅读