1观察者模式
观察者模式,其实就是一个监听,他不完全等同于订阅发布模式。很多人将观察镇等同于订阅发布是错误的。观察者就是一个监听事件的对象,一旦监听到变化则通知给其他对象。
1.1 一个很简单的观察者模式
-------------------------------------------------------------------------
1.1.1定义接口
/** * 天气预报接口 */ public interface Weather { /** * tongzhi * @param weather */ public void notifyWeather(String weather); }
天气接口主要功能是推送天气的信息
1.1.2人群类
天气预报的通知对象是人类,因此人类想要获取天气就要继承天气接口
public class Student implements Weather { private String name; public Student(String name) { super(); this.name = name; } @Override public void notifyWeather(String weather) { if("晴天".equals(weather)){ System.out.println(name+"高高兴兴的去开学!!"); }else if("雾霾".equals(weather)){ System.out.println(name+"吸多两口去上学!"); }else if("刮风".equals(weather)){ System.out.println(name+"在家睡觉!"); }else if("冰雹".equals(weather)){ System.out.println(name+"在家睡觉!"); }else if("下雪".equals(weather)){ System.out.println(name+"等下完再去上学!"); } } }
public class Employee implements Weather { private String name; public Employee(String name) { this.name = name; } @Override public void notifyWeather(String weather) { if("晴天".equals(weather)){ System.out.println(name+"高高兴兴的去上班!!"); }else if("雾霾".equals(weather)){ System.out.println(name+"戴着消毒面具去上班!"); }else if("刮风".equals(weather)){ System.out.println(name+"拖着大石头过来上班!"); }else if("冰雹".equals(weather)){ System.out.println(name+"戴着头盔过来上班!"); }else if("下雪".equals(weather)){ System.out.println(name+"戴着被子过来上班!"); } } }
1.1.3 变化
写一个气象站的类,负责变化天气,然后将变化推送给接收人
public class WeatherStation { //该集合中存储的都是需要收听天气预报的人 //尽量不要让一个类过分依赖于另外一个类。 List<Weather> list = new ArrayList<Weather>(); String[] weathers = {"晴天","雾霾","刮风","冰雹","下雪"}; String weather ;//当前天气 public void addListener(Weather e){//存放接收人 list.add(e); } //更新天气的 方法 public void updateWeather(){ Random random = new Random(); int index = random.nextInt(weathers.length); weather = weathers[index]; System.out.println("当前的天气是: " + weather); } //开始工作,让一个线程去重复执行一件事:更新天气,然后将天气推送给人 public void startWork() { final Random random = new Random(); new Thread(){ public void run() { while(true){ updateWeather(); for(Weather e : list){ e.notifyWeather(weather); } int s = random.nextInt(1000)+3000; // 500 try { Thread.sleep(s); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }.start(); } }
这就是一个最简单的观察者模式了。。
天气站用来充当被观察者的角色,而学生和工人充当观察者。当被观察者天气站一旦发生了变化就会将结果推送给观察者,观察者做出不同的行为。Mina框架中的事件就是基于这种模式的。当会话连接后会触发一个事件进行,当会话关闭会触发一个事件进行,当接收到消息或发送消息成功都会触发一个事件进行。这和发布订阅不同,被观察者发生了变化就会引发观察者的动作,不管观察者愿不愿意。就像学生和工人一样,天气变化了你就要做不同的动作,这是由不得你的。
1.3深入理解观察者
-------------------------------------------------------------------------