java入门 -- 观察者设计模式

/* 观察者设计模式: 

作用: 当一个对象发生指定的动作时,要通知另外一个对象做出相应的处理,类似于事件触发和监听处理。

其他名称:

发布--订阅

模型--视图

源--收听

从属者模式

需求:编写一个气象站和人两个类,当气象更新的时候,要通知人做出相应的处理。

步骤:

1. 定义一个接口,将观察者要通知执行的方法定义在接口中:

2. 当前对象维护接口的引用,当对象发生指定的动作时即可调用指定的处理方法; */

package com.jin.michael;

import java.util.ArrayList;

import java.util.Random;

//定义一个集合来定义规则

interface Weather{public void notifyWeather(String weather);

}

//天气台类

class WeatherStation{

String[] weathers = {"晴天", "阴天", "小雨", "大雨", "冰雹"};

//当前天气String weather;

//添加观察者

ArrayListllistener = new ArrayList();

public void addListener(Weather weather){

llistener.add(weather);

}

//开始工作方法

public void startWork() throws InterruptedException{

//每1-1.5秒跟新一次天气

final Random random = new Random();

new Thread(){

public void run() {

while(true){

int sec = random.nextInt(501)+1000;

try {

Thread.sleep(sec);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

updateWeather();

for(Weather w : llistener){

w.notifyWeather(weather);

}

}

}

}.start();

}

//更新天气

public void updateWeather(){

Random random = new Random();

int index = random.nextInt(weathers.length);

weather = weathers[index];

System.out.println("当前天气是:" + weather);

}

}

//工人类,要收听天气,必须实现规则,根据天气做出相应的处理

class Worker implements Weather{

String name;

public Worker(String name){

this.name = name;

}

public void notifyWeather(String weather){

if("晴天".equals(weather)){

System.out.println(weather+":出去旅游");

}

else if("阴天".equals(weather)){

System.out.println(weather+"去看书");

}

else if("小雨".equals(weather)){

System.out.println(weather+"要带上伞");

}

else if("大雨".equals(weather)){

System.out.println(weather+"去吃火锅");

}

else if("冰雹".equals(weather)){

System.out.println(weather+"在家睡觉");

}

}

}

class Dog implements Weather{

@Override

public void notifyWeather(String weather) {

if("晴天".equals(weather)){

System.out.println(weather+":唱歌");

}

else if("阴天".equals(weather)){

System.out.println(weather+"吃饭");

}

else if("小雨".equals(weather)){

System.out.println(weather+"喝酒");

}

else if("大雨".equals(weather)){

System.out.println(weather+"旅游");

}

else if("冰雹".equals(weather)){

System.out.println(weather+"游泳");

}

}

}

public class Demo05 {

public static void main(String[] args) throws InterruptedException{

Worker worker = new Worker("小王");

Worker worker1 = new Worker("小成");

Dog d1 = new Dog();

Dog d2 = new Dog();

WeatherStation wStation = new WeatherStation();

wStation.addListener(worker);

wStation.addListener(worker1);

wStation.addListener(d2);

wStation.addListener(d1);

wStation.startWork();

}

}

你可能感兴趣的:(java入门 -- 观察者设计模式)