Listener模式

没有什么好说的直接上代码,秒懂

1
2
3
4
5
6
7
8
9
**
* 告警Listener
* @author hubo
* @since 2017-06-30 15:37
**/
public interface AlarmListener {
void alarm(AlarmEvent alarmInfo);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 告警记录到数据库
*
* @author hubo
* @since 2017-06-30 15:40
**/
public class WriteDBListenerImpl implements AlarmListener {
private AlarmLogMapper alarmLogMapper = SpringContextUtil.getBean("alarmLogMapper", AlarmLogMapper.class);
@Override
public void alarm(AlarmEvent alarmInfo) {
alarmLogMapper.insertSelective(alarmInfo); //插入数据库
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 发微信公众号
*
* @author hubo
* @since 2017-06-30 15:40
**/
public class WechatListenerImpl implements AlarmListener {
@Override
public void alarm(AlarmEvent alarmInfo) {
System.out.print("发微信公众号业务");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 发短信提示
*
* @author hubo
* @since 2017-06-30 15:40
**/
public class SMSListenerImpl implements AlarmListener {
@Override
public void alarm(AlarmEvent alarmInfo) {
System.out.print("发短信提示业务....");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class AlarmManager {
private Queue<AlarmListener> listeners = new ConcurrentLinkedQueue<>();
private ExecutorService executorService = Executors.newFixedThreadPool(2);
public void addListener(AlarmListener listener) {
listeners.add(listener);
}
/**
* 执行告警业务
*/
public void executeAlarm(final AlarmEvent alarmInfo) {
for (int i = 0, len = listeners.size(); i < len ; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
listeners.poll().alarm(alarmInfo);
}
});
}
}
}

应用

1
2
3
4
5
6
7
public static void main(String[] args) {
AlarmManager alarmManager = new AlarmManager();
alarmManager.addListener(new WriteDBListenerImpl()); //记录到库
alarmManager.addListener(new WechatListenerImpl()); //微信告警
alarmManager.executeAlarm(alarmInfo);
}