在 android MVP 结构的应用程序中,将字符串资源作为 {path} 传递给 Retrofit 调用的 "correct" 方法是什么?

In an android MVP-structured app, what would be the "correct" way to pass a string resource as {path} to a Retrofit call?

在模型层,我有一个 DataManager class 来处理所有 Retrofit 调用。

改进方法需要 {path} 参数,因为我将所有 REST 端点作为字符串资源存储在单独的 xml 文件中(用于 .gitignore 目的)。

因此,如果我不想将 Context 传递给模型层和演示层(并执行 context.getString),我该如何获取和传递这些参数?

最好的方法是使用像 "Dagger 2" 这样的库或借助依赖倒置来使用依赖注入。

做第一种方式可以参考这个link:(这种方式需要更多的代码和时间但是最佳实践-最推荐在mvp架构中使用-学习有点复杂)

http://www.vogella.com/tutorials/Dagger/article.html

要执行第二种方法,请执行以下操作:(更少的代码有点脏 - 如果您不想使用 dagger,请使用它)

要提供这种需要来自 android 而不是纯粹 java 的东西的变量,您可以创建一个接口 class 并添加一些方法来满足您的需求。代码将是这样的:

public interface Provider {
public String providePath();
}

假设您的模型和演示者位于单独的纯 java 模块中,您必须将此接口添加到模块中以防止循环依赖。然后在 android class 中实现此接口,并在每次通话中将其发送给演示者。

public class ProviderImpl implements Provider {

 private Context ctx;
 public ProviderImpl(final Context ctx) {
    this.ctx = ctx;
}

@Override
public string providePath() {
    //provide the path from resources
}
}

使用这种方式,您可以将每个新需求作为一种方法添加到您的 Provider 接口,并在 Presenter 中使用它。 您必须在演示者中获得一个 Provider 变量作为参数。

我会自己使用 DAGGER,因为它更干净,也是最佳实践。