Android 多模块暴露接口调用功能

在模块化开发中,时不时会遇到跨模块调用功能,引入了ARouter可以做到跨模块调用,那如果项目没有引入ARouter呢,那这里可以自己做多模块暴露接口调用功能。

这里示例做了从业务模块中调用主app module中的一个用户信息,从角色上分为app模块,common模块,业务模块三个模块。

在公共模块common模块中

用户实体类:

data class UserBean(val id: String, val name: String)

ServiceCreator类:

public interface ServiceCreator {
    T create();
}

ServiceManager类:用于对暴露接口和实现类的绑定关系:

public final class ServiceManager {
    private static final ConcurrentHashMap sServices = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap> sServiceCreators = new ConcurrentHashMap<>();

    private ServiceManager() {
    }

    @SuppressWarnings("unchecked")
    public static  T getService(@NonNull Class iCls) {
        return getService(iCls.getName());
    }

    @SuppressWarnings("unchecked")
    public static  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 creator = (ServiceCreator) sServiceCreators.get(name);
                    if (creator != null) {
                        service = creator.create();
                        sServices.put(name, service);
                        sServiceCreators.remove(name);
                    }
                }
            }
        }
        return service;
    }

    public static  void registerService(@NonNull Class iCls, @NonNull T obj) {
        registerService(iCls.getName(), obj);
    }

    public static  void registerService(@NonNull String name, @NonNull T obj) {
        sServices.put(name, obj);
    }

    public static  void registerService(@NonNull Class iCls, @NonNull ServiceCreator creator) {
        registerService(iCls.getName(), creator);
    }

    public static  void registerService(@NonNull String name, @NonNull ServiceCreator creator) {
        sServiceCreators.put(name, creator);
    }

    public static  void unregisterService(@NonNull Class iCls) {
        unregisterService(iCls.getName());
    }

    public static  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)

你可能感兴趣的:(Android 多模块暴露接口调用功能)