commons-lang3 事件机制 <EventListenerSupport>
俗话说,站在巨人肩上,可以使我们走的更远
使用已有的java组件,可以提高我们的开发效率,减少出错几率,apache commons中包含有很多这样的组将,commons-lang3就是其中的一个,当前存在commons-lang和commons-lang3两个组件,后者可看做是前者的升级,前者内容已经迁移到后者,所以我们在使用时,直接使用后者即可
commons-lang3中添加了事件处理机制。EventListenerSupport为event包下的一个事件监听模块。当我们在完成一件事件时,需要通知其他模块做一些处理,就可以使用该功能进行处理
比如:商家发货后,需要通知快递小哥取货,并且通知用户商家已接单。使用该功能实现起来也很简单.
maven依赖中加入commons-lang3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.demo</groupId> <artifactId>langdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>langdemo</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version> </dependency> </dependencies> </project>
接口
package com.demo.langdemo.listeners; public interface IListeners { // 接收消息 void receive(); }
用户
package com.demo.langdemo.listeners.impl; import com.demo.langdemo.listeners.IListeners; /** * 用户 */ public class User implements IListeners { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void receive() { System.out.println("\"" + this.getName() + "\"收到信息:已发货"); } }
快递员
package com.demo.langdemo.listeners.impl; import com.demo.langdemo.listeners.IListeners; /** * 快递员 */ public class Courier implements IListeners { private String name; public Courier(String name) { this.name = name; } public String getName() { return name; } public void receive() { System.out.println("\"" + this.getName() + "\"收到信息: 有快递需要发送"); } }
测试类
package com.demo.langdemo; import org.apache.commons.lang3.event.EventListenerSupport; import com.demo.langdemo.listeners.IListeners; import com.demo.langdemo.listeners.impl.Courier; import com.demo.langdemo.listeners.impl.User; public class App { public static void main(String[] args) { EventListenerSupport<IListeners> listenersEvent = new EventListenerSupport<>(IListeners.class); // 注册监听 listenersEvent.addListener(new Courier("快递员小马")); listenersEvent.addListener(new User("用户小刘")); listenersEvent.fire().receive(); } }
运行结果如下
若要新加一个监听,比如通知第三方已发货,则新建一个类实现LListener接口
package com.demo.langdemo.listeners.impl; import com.demo.langdemo.listeners.IListeners; public class ThirdParty implements IListeners { private String name; public ThirdParty(String name) { this.name = name; } public String getName() { return name; } @Override public void receive() { System.out.println("\"" + this.getName() + "\"收到信息:已发货"); } }
注册接口(接口注册要在fire方法之前)
listenersEvent.addListener(new ThirdParty("第三方公司"));
运行测试