1.定义
监听器模式,主要由3个角色组成,事件、监听器和事件发布器,其核心流程是由事件发布器发布事件,在事件发布前后放置监听器。

2.优点
监听器模式更加灵活,可以对不同事件作出相应。

3.代码示例
(1).事件

public abstract class WeatherEvent {
public abstract String getWeather();
}
public class RainEvent extends WeatherEvent {
@Override
public String getWeather() {
return "rain";
}
}
public class SnowEvent extends WeatherEvent {
@Override
public String getWeather() {
return "snow";
}
}

(2).监听器

public interface WeatherListener {
void onWeatherEvent(WeatherEvent event);
}
public class RainListener implements WeatherListener {

@Override
public void onWeatherEvent(WeatherEvent event) {
if (event instanceof RainEvent) {
System.out.println("hello " + event.getWeather());
}
}
}
public class SnowListener implements WeatherListener {

@Override
public void onWeatherEvent(WeatherEvent event) {
if (event instanceof SnowEvent) {
System.out.println("hello " + event.getWeather());
}
}
}

(3).广播器

public interface EventMulticaster {
//广播事件
void multicastEvent(WeatherEvent event);

//添加事件
void addListener(WeatherListener weatherListener);

//移除事件
void removeListener(WeatherListener weatherListener);
}
public abstract class AbstractEventMulticaster implements EventMulticaster {
private List<WeatherListener> listenerList = new ArrayList<>();

@Override
public void multicastEvent(WeatherEvent event) {
doStart();
//每个监听器都需要判断一下事件是否被自己监听了
for (WeatherListener weatherListener : listenerList) {
weatherListener.onWeatherEvent(event);
}
doEnd();
}

protected abstract void doStart();

protected abstract void doEnd();

@Override
public void addListener(WeatherListener weatherListener) {
listenerList.add(weatherListener);
}

@Override
public void removeListener(WeatherListener weatherListener) {
listenerList.remove(weatherListener);
}
}
public class WeatherEventMulticaster extends AbstractEventMulticaster {

@Override
protected void doStart() {
System.out.println("begin broadcast weather event");
}

@Override
protected void doEnd() {
System.out.println("end broadcast weather event");
}
}

(4).测试

public class Test {
public static void main(String[] args) {
//构造一个广播器
WeatherEventMulticaster eventMulticaster = new WeatherEventMulticaster();

//创建两个监听器
RainListener rainListener = new RainListener();
SnowListener snowListener = new SnowListener();
//将监听器添加到广播器当中
eventMulticaster.addListener(rainListener);
eventMulticaster.addListener(snowListener);

//广播器广播下雪事件
eventMulticaster.multicastEvent(new SnowEvent());
//广播器广播下雨事件
eventMulticaster.multicastEvent(new RainEvent());

System.out.println("--------------------");
eventMulticaster.removeListener(rainListener);

//广播器广播下雪事件
eventMulticaster.multicastEvent(new SnowEvent());
//广播器广播下雨事件
eventMulticaster.multicastEvent(new RainEvent());
}
}