观察者设计模式
整个流程使用天气预报和用户的行为来作为实例,天气预报每次发生变化,则用户需要根据天气做相应的反应,如天气雨则用户带伞,天气寒冷则用户多穿衣服等
一、观察者和被观察者,被观察者直接持有观察者引用 - 被观察者通知观察者
二、被观察者持有观察者,被观察者统一实现监听器接口的形式- 被观察者通过监听器通知观察者
三、被观察者持有观察者集合的模式 - 被观察者通过监听器通知N多个观察者
四、被观察者通过,事件来通知观察者(通过事件来控制是否通知) - 这个需要把例子中的type变成事件类来进一步处理,方法内部对事件类型进行判断来做处理
五、被观察者通过发布接口统一发布通知
第三种实例的例子: 天气预报监听器,用户,
观察者接口:
package com.test.moshi; //天气预报监听器 public interface WeatherListener { public void doSomeThing(int type, String str); }
用户类:
View Code
package com.test.moshi; /** * 用户 */ public class User implements WeatherListener{ String name ; public User(String name) { this.name = name; } public void doSomeThing(int type, String str){ // System.out.println( "通知了用户天气变化"); if(type==1){ System.out.println(name+"需要做些事情:"+ str ); } if(type==2){ System.out.println(name+"需要做些事情:"+ str ); } if(type==3){ System.out.println(name+"需要做些事情:"+ str ); } if(type==4){ System.out.println(name+"需要做些事情:"+ str ); } } }
天气预报
package com.test.moshi; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 天气预报 对 人们行为的影响 * 用户是观察者,一旦天气发生变化则通知用户做相应的应对 */ public class WeatherPredictImpl { List<WeatherListener> userList = new ArrayList<>(); private static Map<Integer,String> wheatherItem = new HashMap<>(); static { wheatherItem.put(1,"晴天"); wheatherItem.put(2,"大雨"); wheatherItem.put(3,"大雪"); wheatherItem.put(4,"寒风凛冽"); } private int type ; private String weatherName; //天气变更 public void weatherChange( int weatherType){ this.weatherName = wheatherItem.get(weatherType); this.type = weatherType; notifyAllUsers(); } //需要对观察者做维护 public void addUser(User user){ userList.add( user ); } /** * 通知用户天气变更 */ private void notifyAllUsers( ){ userList.stream().forEach(weatherListener->weatherListener.doSomeThing(type,weatherName)); } }
测试类
测试类: package com.test.moshi; public class TestProdict { public static void main(String[] args) throws InterruptedException { WeatherPredictImpl weatherPredict = new WeatherPredictImpl() ; weatherPredict.addUser(new User("小李飞刀")); // weatherPredict.addUser(new User("张飞")); // weatherPredict.addUser(new User("赵云")); weatherPredict.weatherChange( 1); Thread.currentThread().sleep(2000); weatherPredict.weatherChange( 2); Thread.currentThread().sleep(2000); weatherPredict.weatherChange( 3); } }