------- android培训、java培训、期待与您交流! ----------
黑马程序员---观察者设计模式
一:设计模式是一套被反复使用丶多数人知道的,经过分类的代码设计经验总结。使用设计模式是为了可重复使用,让代码更容易被他人理解,保证代码可靠性。
观察者模式完美的将观察者和被观察的对象分离开。
有多个观察者时,不可以依赖特定的通知次序。
定义:当一个事物发生了相应的动作事件的时候,那么要通知另外一个事物做出相应的处理...
应用场景:许多GUI框架。
下面编写一个天气订阅的例子深入理解观察者设计模式:
需求:编写一个气象站,员工类,气象站不断的在更新天气,当更新天气的时候,员工就要根据天气的变化做出相应的处理...
1:描述一个气象站:
package com.watcher;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
//描述气象站
public class WeatherStation {
//天气类型存入数组中
String[] weathers = {"晴天","阴天","大雪","小雨"};
//当前的天气
String weather;
//存储订阅天气接口的实现类
List<BookWeather> list = new ArrayList<BookWeather>();
public void add(BookWeather e) {
list.add(e);
}
//开始工作1-1.5秒更新一次天气
public void startWork(){
new Thread(){//使用多线程跟新天气。
public void run(){
try {
while(true){
updataWeather();//更新天气
for(BookWeather e:list){
e.notifyWeather(weather);
}
Random random = new Random();
int time = random.nextInt(501)+1000;
Thread.sleep(time);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
//更新天气的方法
public void updataWeather(){
//随机产生天气
weather = weathers[new Random().nextInt(weathers.length)];
System.out.println("当前天气是:"+weather);
}
}
2:定义一个订阅天气的接口,只要实现该接口的类,气象站就会去通知。
package com.watcher;
//订阅天气的接口类
public interface BookWeather {
public void notifyWeather(String weather);
}
3:描述一个员工
package com.watcher;
//描述员工类
public class Emp implements BookWeather{
String name;
public Emp(String name){
this.name=name;
}
//员工要根据天气做出相应的处理动作
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+"风雨无阻上班去...");
}
}
}
4:主程序
package com.watcher;
public class MainClass {
public static void main(String[] args) {
//创建一个员工对象
Emp emp = new Emp("牧尘");
Emp emp2 = new Emp("穆珊珊");
//创建一个气象站对象
WeatherStation station = new WeatherStation();
station.add(emp);
station.add(emp2);
//开始工作
station.startWork();
}
}
当气象站每次更新天气时都会出通知实现订阅天气接口的实现类,就是观察者设计模式。
观察者设计模式:只需要把要通知对方事物的方法抽取出来一个接口,然后在本类维护一个接口的引用即可。