观察者设计模式:
观察者设计模式解决的问题时当一个对象发生指定的动作时,要通过另外一个对象做出相应的处理。
下面我们可以通过天气的播报来实现观察者模式
编写一个气象站、一个工人、一个学生三个类,当气象站更新天气 的时候,要通知人做出相应的处理。
观察者设计模式的步骤:
1. 当前目前对象发生指定的动作是,要通知另外一个对象做出相应的处理,这时候应该把对方的相应处理方法定义在接口上。
2. 在当前对象维护接口的引用,当当前对象发生指定的动作这时候即可调用接口中的方法了。
编写一个气象站类
/**
* 气象台播报天气
* @author evan_qb
*
*/
public class WeatherStation {
String[] weathers = { "晴天", "雾霾", "刮风", "冰雹", "下雪" };
// 当前天气
String weather;
// 定义一个Weather接口,当谁需要知道天气的时候就实现这个接口
// 创建一个集合用于存储需要收听的人
ArrayList<Weather> list = new ArrayList<>();
public void addListener(Weather e) {
list.add(e);
}
//气象台一直工作(报天气)
public void startWork(){
final Random random = new Random();
new Thread(){
@Override
public void run() {
while(true){
//每隔3-3.5秒更新一次数据
updateWeather();
for (Weather e : list) {
e.notifyWeather(weather);
}
//定义随机数 3000~3500
int time = random.nextInt(501) + 3000;
try {
Thread.sleep(time);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}.start();
}
// 定义更新天气的方法
public void updateWeather() {
Random random = new Random();
int index = random.nextInt(4);
// 随机获取天气
weather = weathers[index];
System.out.println("-----------当前的天气是" + weather + "-----------");
}
}
定义一个接口,谁实现这个接口就给谁播报天气
/**
* 通知天气的接口
* @author evan_qb
*
*/
public interface Weather {
//通知所有实现这个接口的人天气状况
public void notifyWeather(String weather);
}
然后建立工人类和学生类实现Weather接口
工人类
/**
* 工人
* 实现Weather接口
* @author evan_qb
*
*/
public class Emp implements Weather{
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+"戴着头盔过来上班!");
}else if("下雪".equals(weather)){
System.out.println(name+"戴着被子过来上班!");
}
}
}
学生类
/**
* 学生
* @author evan_qb
*/
public class Student implements Weather{
String name;
public Student(String name) {
super();
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+"在家睡觉!");
}else if("下雪".equals(weather)){
System.out.println(name+"等下完再去上学!");
}
}
}
这样就实现了对特定对象播报天气
下面我们就来测试一波
public class WeatherMain {
public static void main(String[] args) {
//工人
Emp emp = new Emp("小白");
//学生
Student student = new Student("evan_qb");
WeatherStation station = new WeatherStation();
station.addListener(emp);
station.addListener(student);
station.startWork();
}
}
运行结果如下: