标签:
观察者模式(Observer Patterns)
观察者模式:定义了对象间一对多的依赖,这样一来,当一个对象的状态改变时,它的所有依赖都会自动收到通知并自动更新。
现在有一种需求:IOS系统的手机和Android的手机都去订阅天气预报。那么提供天气情况的就是一个主题。而Iphone和Android就是观察者,来观察天气预报的变化。当天气发生变化的时候在他们二者都能够数据同步。
1.创建观察者(Observer)接口
public interface Observer { public void update(int low, int high, String weather); }
2.创建主题(Subject)接口
public interface Subject { public void addObserver(Observer observer); public void removeObserver(Observer observer); public void notifyObserver(); }
3.添加Weather对象实现Subject接口
public class WeatherData implements Subject{ private int low ; private int high; private String weather; private List<Observer> list = new ArrayList<Observer>();//list集合中放的都是Observer的实现类 //get方法 public int getLow() { return low; } public int getHigh() { return high; } public String getWeather() { return weather; } //设置low high weather public void setData(int low ,int high,String weather){ this.low = low ; this.high = high; this.weather = weather; notifyObserver(); } //添加观察者 public void addObserver(Observer observer) { if(!list.contains(observer)){ list.add(observer); } } //删除观察者 public void removeObserver(Observer observer) { if(list.contains(observer)){ list.remove(observer); } } //通知 public void notifyObserver() { for(Observer o : list){ o.update(getLow(),getHigh(),getWeather()); } } }
4.分别创建Iphone和Android类实现Observer接口
public class Iphone implements Observer{ public void display(int low ,int high ,String weather){ System.out.println("Iphone:"+low + high + weather); } public void update(int low, int high, String weather) { display(low, high, weather); } }
public class Android implements Observer{ public void display(int low ,int high ,String weather){ System.out.println("Android:"+low + high + weather); } public void update(int low, int high, String weather) { display(low, high, weather); } }
5.测试
public class test { public static void main(String[] args) { WeatherData wd = new WeatherData(); Android android = new Android(); Iphone iphone = new Iphone(); wd.addObserver(android);//把android添加进去 wd.addObserver(iphone );//把iphone 添加进去 wd.setData(11, 33,"晴天"); //当改变主题时,android, iphone 都会收到通知 wd.setData(13, 23, "阴天"); } }
标签:
原文地址:http://my.oschina.net/u/1995545/blog/363388