观察者模式(订阅发布模式)及实例Demo

1、观察者模式,又称订阅发布模式,其架构如下:

观察者模式(订阅发布模式)及实例Demo_第1张图片

2、实例demo——订阅天气,发布天气

1>WeatherSubject  目标类

public class WeatherSubject {

 

   private List observers = new ArrayList();

  

   public void attach(Observer observer){

     observers.add(observer);

   }

  

   public void detach(Observer observer){

     observers.remove(observer);

   }

  

   protected void notifyObservers(){

     for(Observer observer : observers){

        observer.update(this);

     }

   }

  

}

2> 具体的目标类

public class ConcreteWeatherSubject extends WeatherSubject {

 

   private String weatherContent;

 

   public String getWeatherContent() {

     return weatherContent;

   }

 

   public void setWeatherContent(String weatherContent) {

     this.weatherContent = weatherContent;

     this.notifyObservers();

   }

 

 

}

 

3> 观察者

public interface Observer {

  

   public void update(WeatherSubject subject);

  

}

 

4> 具体的观察者

public class ConcreteObserver implements Observer {

 

   private String observerName;

   private String weatherContent;

   private String remindThing;

  

   @Override

   public void update(WeatherSubject subject) {

     weatherContent = ((ConcreteWeatherSubject)subject).getWeatherContent();

     System.out.println(observerName + "收到了" + weatherContent + " ," + remindThing);

   }

 

   public String getObserverName() {

     return observerName;

   }

 

   public void setObserverName(String observerName) {

     this.observerName = observerName;

   }

 

   public String getWeatherContent() {

     return weatherContent;

   }

 

   public void setWeatherContent(String weatherContent) {

     this.weatherContent = weatherContent;

   }

 

   public String getRemindThing() {

     return remindThing;

   }

 

   public void setRemindThing(String remindThing) {

     this.remindThing = remindThing;

   }

  

  

 

}

5> test 类

public class test {

 

   public static void main(String[] args) {

     //1.创建目标

     ConcreteWeatherSubject weather = new ConcreteWeatherSubject();

  

     //2.创建观察者

     ConcreteObserver observerGirl = new ConcreteObserver();

     observerGirl.setObserverName("girl");

     observerGirl.setRemindThing("go shopping");

    

     ConcreteObserver observerBoy = new ConcreteObserver();

     observerBoy.setObserverName("boy");

     observerBoy.setRemindThing("play football");

    

     //3.注册观察者

     weather.attach(observerGirl);

     weather.attach(observerBoy);

    

     //4.目标发布天气

     weather.setWeatherContent("a nice day!");

   }

 

}

 

测试结果:

girl收到了a nice day! ,go shopping
boy收到了a nice day! ,play football
 

你可能感兴趣的:(设计模式)