Listener模式 发表于 2017-07-16 12:10:52 | 分类于 设计模式 | 阅读次数 字数统计 239 | 阅读时长 1 没有什么好说的直接上代码,秒懂 123456789** * 告警Listener * @author hubo * @since 2017-06-30 15:37 **/public interface AlarmListener { void alarm(AlarmEvent alarmInfo);} 123456789101112131415/** * 告警记录到数据库 * * @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); //插入数据库 }} 12345678910111213/** * 发微信公众号 * * @author hubo * @since 2017-06-30 15:40 **/public class WechatListenerImpl implements AlarmListener { @Override public void alarm(AlarmEvent alarmInfo) { System.out.print("发微信公众号业务"); }} 12345678910111213/** * 发短信提示 * * @author hubo * @since 2017-06-30 15:40 **/public class SMSListenerImpl implements AlarmListener { @Override public void alarm(AlarmEvent alarmInfo) { System.out.print("发短信提示业务...."); }} 123456789101112131415161718192021222324public 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); } }); } }} 应用1234567public static void main(String[] args) { AlarmManager alarmManager = new AlarmManager(); alarmManager.addListener(new WriteDBListenerImpl()); //记录到库 alarmManager.addListener(new WechatListenerImpl()); //微信告警 alarmManager.executeAlarm(alarmInfo);}