在模块化开发中,时不时会遇到跨模块调用功能,引入了ARouter可以做到跨模块调用,那如果项目没有引入ARouter呢,那这里可以自己做多模块暴露接口调用功能。
这里示例做了从业务模块中调用主app module中的一个用户信息,从角色上分为app模块,common模块,业务模块三个模块。
在公共模块common模块中
用户实体类:
data class UserBean(val id: String, val name: String)
ServiceCreator类:
public interface ServiceCreator<T> {
T create();
}
ServiceManager类:用于对暴露接口和实现类的绑定关系:
public final class ServiceManager {
private static final ConcurrentHashMap<String, Object> sServices = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, ServiceCreator<?>> sServiceCreators = new ConcurrentHashMap<>();
private ServiceManager() {
}
@SuppressWarnings("unchecked")
public static <T> T getService(@NonNull Class<T> iCls) {
return getService(iCls.getName());
}
@SuppressWarnings("unchecked")
public static <T> T getService(@NonNull String name) {
T service = (T) sServices.get(name);
if (service == null) {
synchronized (sServices) {
service = (T) sServices.get(name);
if (service == null) {
ServiceCreator<T> creator = (ServiceCreator) sServiceCreators.get(name);
if (creator != null) {
service = creator.create();
sServices.put(name, service);
sServiceCreators.remove(name);
}
}
}
}
return service;
}
public static <T> void registerService(@NonNull Class<T> iCls, @NonNull T obj) {
registerService(iCls.getName(), obj);
}
public static <T> void registerService(@NonNull String name, @NonNull T obj) {
sServices.put(name, obj);
}
public static <T> void registerService(@NonNull Class<T> iCls, @NonNull ServiceCreator<T> creator) {
registerService(iCls.getName(), creator);
}
public static <T> void registerService(@NonNull String name, @NonNull ServiceCreator<T> creator) {
sServiceCreators.put(name, creator);
}
public static <T> void unregisterService(@NonNull Class<T> iCls) {
unregisterService(iCls.getName());
}
public static <T> void unregisterService(@NonNull String name) {
sServices.remove(name);
sServiceCreators.remove(name);
}
public static void clearAll(){
sServices.clear();
sServiceCreators.clear();
}
}
业务模块中
声明需要获取能力的接口:
public interface IModuleConnect {
UserBean getUserBean();
}
app模块中:
实现该接口功能:
public class IModuleConnectImp implements IModuleConnect {
@Override
public UserBean getUserBean() {
UserBean userBean = new UserBean("", "IModuleConnectImp");
return userBean;
}
}
在application中
注册该暴露接口和现在类:
//注册service
ServiceManager.registerService(IModuleConnect::class.java, IModuleConnectImp())
在业务模块中:
从ServiceManager的hashmap中获取实现类,调用实现类实现的方法:
val service = ServiceManager.getService(IModuleConnect::class.java)
网友评论