例如一个转跳服务(在app模块下实现,需要在其他模块调用)
- 在最底层Base模块中顶一个跳转服务的接口,里面定义两个方法
interface IIProvider {
fun startLoginActivity(from: String)
fun startMainActivity(from: String)
}
- 在app模块下实现这个实例,并实现其两个页面跳转的接口
class JumpProvider : IIProvider {
override fun startLoginActivity(from: String) {
Log.d(TAG, "前往登录页面")
}
override fun startMainActivity(from: String) {
Log.d(TAG, "前往主页面")
}
}
Kotlin高阶函数的方式实现(最简单)
- 在Base模块下定义一个工具类,用于获取跳转服务的实例,定义一个变量类型是一个函数,函数的返回值是IIProvider
object JumpUtil {
var init: () -> IIProvider? = { null }
}
- 在application中将实例对象传给JumpUtil
override fun onCreate() {
super.onCreate()
JumpUtil.init = { JumpProvider() }
}
private fun gotoMain() {
val provider = JumpUtil.init.invoke()
provider?.startMainActivity("EditorActivity")
}
Kotlin接口的方式实现
object JumpTool {
var getProvider: GetProvider? = null
fun init(getProvider: GetProvider) {
this.getProvider = getProvider
}
}
interface GetProvider {
fun getInstance(): IIProvider
}
- application中实现接口,并将JumpProvider实例传入
override fun onCreate() {
super.onCreate()
JumpTool.init(object : GetProvider {
override fun getInstance(): IIProvider {
return JumpProvider()
}
})
}
private fun gotoSearch() {
val provider = JumpTool.getProvider?.getInstance()
provider?.startSearchActivity("EditorActivity")
}
Java接口方式实现(其他同Kotlin接口方式)
public class JumpTest {
private JumpTest() {
}
private static class Holder {
public final static JumpTest instance = new JumpTest();
}
public static JumpTest getInstance() {
return Holder.instance;
}
private GetProvider getProvider;
public void setProvider(GetProvider instance) {
this.getProvider = instance;
}
public IIProvider getProvider() {
if (getProvider != null) {
return getProvider.getInstance();
}
return null;
}
}
JumpTest.getInstance().setProvider(object : GetProvider {
override fun getInstance(): IIProvider {
return JumpProvider()
}
})
private fun gotoSearch2() {
val provider = JumpTest.getInstance().provider
provider?.startSearchActivity("EditorActivity")
}