事件驅(qū)動
前情提要
上文中分別使用了依賴注入和觀察者模式實現(xiàn)需求:用戶注冊成功,初始化用戶信息。


上述兩種實現(xiàn)存在同一個問題,當(dāng)注冊完成需要好友服務(wù)初始化好友列表,兩者都需要修改自身代碼,使用依賴注入的方法需要注入新的依賴,且需要修改調(diào)用代碼(register),觀察者模式實現(xiàn)需要修改代碼獲取新的觀察者,并讓新觀察者注冊進入主題中,耦合程度高,且兩者都違背了開閉原則進行編碼,那么是否可以在不修改代碼的前提下進行上述需求開發(fā)(不使用MQ)。
觀察者模式實現(xiàn)的不足
1.在調(diào)用前顯式的獲取觀察者實例
2.在調(diào)用前顯式的注冊進入主題
出現(xiàn)這個問題的原因是主題調(diào)用通知接口前必須要明確知道該通知哪些對象,獲取實例和注冊的目的是為了讓主題和觀察者進行綁定(主題組合了觀察者的集合)。
public void register(){
RegisteSub concurrentSubject = new RegisteSub();
// ObserverInterface pointsObserver = new PointsObserver();
// UserObserver userObserver = new UserObserver();
// concurrentSubject.addListener(pointsObserver);
// concurrentSubject.addListener(userObserver);
RegisterService registerService = new RegisterService();
boolean success = registerService.registerByTel();
if(success){
concurrentSubject.notifyObserver();
}
}
此時的模型

concurrentSubject.notifyObserver();
事件驅(qū)動是如何做到解耦的

1.事件發(fā)布器不執(zhí)行通知監(jiān)聽器邏輯,只聚合事件廣播器,和對外提供一個發(fā)布事件方法。(可復(fù)用)
2.事件廣播器負責(zé)向監(jiān)聽器廣播事件,事件廣播器需要獲取對應(yīng)事件的監(jiān)聽器。(可復(fù)用)
3.事件,解耦的關(guān)鍵,監(jiān)聽器和事件進行綁定,不是和事件發(fā)布器,事件廣播器進行綁定。
4.監(jiān)聽器,類似觀察者,監(jiān)聽器和事件進行綁定。
理清了上述概念,就會有以下疑問:
核中核:監(jiān)聽器是如何與事件綁定的?事件廣播器是如何獲取到xx事件的監(jiān)聽器?
A:在監(jiān)聽器上使用注解,指定監(jiān)聽器監(jiān)聽的事件,完成事件和監(jiān)聽器的綁定,廣播器根據(jù)事件獲得事件的監(jiān)聽器完成廣播行為。


具體代碼
以下代碼都可以在我的git倉庫找到 https://gitee.com/hxh953/copy-spring-event-driven
public interface ApplicationEvent {
}
public interface ApplicationListener {
void onApplicationEvent(ApplicationEvent event);
}
public interface ApplicationEventPublisher {
void publishEvent(ApplicationEvent event);
}
public class registeFailEvent implements ApplicationEvent{
}
public class registeSuccessEvent implements ApplicationEvent{
public registeSuccessEvent(){
System.out.println("注冊成功");
}
}
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface WhichToListen {
Class[] value();
}
@WhichToListen(value = {registeSuccessEvent.class,registeFailEvent.class})
public class UserListener implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof registeSuccessEvent){
System.out.println("用戶系統(tǒng):初始化用戶信息");
}
if(event instanceof registeFailEvent){
System.out.println("啥也不做,測試是不是可以監(jiān)聽兩個事件");
}
}
}
@WhichToListen(value = registeSuccessEvent.class)
public class PointsListener implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof registeSuccessEvent){
System.out.println("積分系統(tǒng):初始化積分");
}
}
}
public class ApplicationMulticaster {
List<ApplicationListener> listeners ;
boolean addListener(ApplicationListener listener){
if(listeners == null){
listeners = new ArrayList<>();
}
return listeners.add(listener);
}
boolean removeListener(ApplicationListener listener){
if(listeners == null){
return false;
}
return listeners.remove(listener);
}
/**
* 向所有監(jiān)聽本事件的監(jiān)聽器器廣播
* @param event
*/
public void multicastEvent(ApplicationEvent event){
List<ApplicationListener> listeners = getApplicationListeners(event);
listeners.forEach(item -> item.onApplicationEvent(event));
}
//獲取監(jiān)聽了該事件的監(jiān)聽器集合
List<ApplicationListener> getApplicationListeners(ApplicationEvent event){
if (listeners == null){
this.listeners = ClassUtil.getListenersByEvent(event);
}
return listeners;
}
}
public class ClassUtil {
/**
* 獲得實現(xiàn)ApplicationListener接口,且被WitchToListen注解,注解value值包含xx的所有監(jiān)聽類
*/
public static List<ApplicationListener> getListenersByEvent(ApplicationEvent e) {
List<ApplicationListener> listeners = null;
Class c = ApplicationListener.class;
if (c.isInterface()) {
// 獲取當(dāng)前的包名
String packageName = c.getPackage().getName();
// 獲取當(dāng)前包下以及子包下所以的類
List<Class<?>> allClass = getClasses(packageName);
if (allClass != null) {
listeners = new ArrayList<ApplicationListener>();
for (Class classes : allClass) {
// 判斷是否是同一個接口
if (c.isAssignableFrom(classes)) {
// 本身不加入進去
if (!c.equals(classes)) {
//classes.getDeclaredAnnotation(WhichToListen.class)
WhichToListen an = (WhichToListen) classes.getAnnotation(WhichToListen.class);
// Annotation a = classes.getAnnotation(WhichToListen.class);
Class[] listenClasses = an.value();
for (Class ac : listenClasses) {
if(ac.getName().equals(e.getClass().getName())){
try {
Object o = classes.getDeclaredConstructor().newInstance();
listeners.add((ApplicationListener) o);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
}
}
}
return listeners;
}
/*
* 取得某一類所在包的所有類名 不含迭代
*/
public static String[] getPackageAllClassName(String classLocation, String packageName) {
// 將packageName分解
String[] packagePathSplit = packageName.split("[.]");
String realClassLocation = classLocation;
int packageLength = packagePathSplit.length;
for (int i = 0; i < packageLength; i++) {
realClassLocation = realClassLocation + File.separator + packagePathSplit[i];
}
File packeageDir = new File(realClassLocation);
if (packeageDir.isDirectory()) {
String[] allClassName = packeageDir.list();
return allClassName;
}
return null;
}
/**
* 從包package中獲取所有的Class
*
* @param
* @return
*/
public static List<Class<?>> getClasses(String packageName) {
// 第一個class類的集合
List<Class<?>> classes = new ArrayList<Class<?>>();
// 是否循環(huán)迭代
boolean recursive = true;
// 獲取包的名字 并進行替換
String packageDirName = packageName.replace('.', '/');
// 定義一個枚舉的集合 并進行循環(huán)來處理這個目錄下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
// 循環(huán)迭代下去
while (dirs.hasMoreElements()) {
// 獲取下一個元素
URL url = dirs.nextElement();
// 得到協(xié)議的名稱
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服務(wù)器上
if ("file".equals(protocol)) {
// 獲取包的物理路徑
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式掃描整個包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定義一個JarFile
JarFile jar;
try {
// 獲取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// 從此jar包 得到一個枚舉類
Enumeration<JarEntry> entries = jar.entries();
// 同樣的進行循環(huán)迭代
while (entries.hasMoreElements()) {
// 獲取jar里的一個實體 可以是目錄 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/開頭的
if (name.charAt(0) == '/') {
// 獲取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定義的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"結(jié)尾 是一個包
if (idx != -1) {
// 獲取包名 把"/"替換成"."
packageName = name.substring(0, idx).replace('/', '.');
}
// 如果可以迭代下去 并且是一個包
if ((idx != -1) || recursive) {
// 如果是一個.class文件 而且不是目錄
if (name.endsWith(".class") && !entry.isDirectory()) {
// 去掉后面的".class" 獲取真正的類名
String className = name.substring(packageName.length() + 1, name.length() - 6);
try {
// 添加到classes
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式來獲取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive,
List<Class<?>> classes) {
// 獲取此包的目錄 建立一個File
File dir = new File(packagePath);
// 如果不存在或者 也不是目錄就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 如果存在 就獲取包下的所有文件 包括目錄
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定義過濾規(guī)則 如果可以循環(huán)(包含子目錄) 或則是以.class結(jié)尾的文件(編譯好的java類文件)
public boolean accept(File file) {
return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
}
});
// 循環(huán)所有文件
for (File file : dirfiles) {
// 如果是目錄 則繼續(xù)掃描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java類文件 去掉后面的.class 只留下類名
String className = file.getName().substring(0, file.getName().length() - 6);
try {
// 添加到集合中去
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
public class Test {
public static void main(String[] args) {
ApplicationEvent successEvent = new registeSuccessEvent();
ApplicationEventPublisher applicationPublisher = new ApplicationPublisher();
applicationPublisher.publishEvent(successEvent);
}
}
上面是我的事件驅(qū)動實現(xiàn),無須修改代碼,增加代碼就可以實現(xiàn)開頭的需求。
spring中提供了事件驅(qū)動的實現(xiàn),且可以指定廣播器向監(jiān)聽器廣播的順序,建議閱讀源碼,畢竟比我的豐富很多。