在 MVP 模型的构造函数参数中使用 Context 是一种不好的做法吗?

Is it a bad practice to have Context in MVP Model's constructor parameter?

我正在尝试使用 MVP 模式检查互联网连接。为此,我有一个 class MyAppUtil ,它在其构造函数中采用 Context 。这是我的 MVP 模型 class,我正在使用 MyAppUtil.checkConnection(context) 检查互联网连接:

public class MainActivityInterectorImpl implements MainActivityContract.IInterector{

Context context;

MainActivityInterectorImpl(Context context) {
    this.context = context;
}

@Override
public void getData(OnFinishedListener onFinishedListener) {
    boolean result =  MyAppUtil.checkConnection(context);
    if (result == true) {
        onFinishedListener.onSuccess();
    } else {
        onFinishedListener.onFailure();
    }
}
}

在 VIEW 中,我按以下方式初始化演示器:

presenter = new MainActivityPresenterImpl(this, new MainActivityInterectorImpl(this));

如您所见,我在 MVP 模型中使用 Context。这在 MVP 模式中可以吗?还有更好的方法吗?

是的,这是不好的做法。制作连接检查器或类似东西的包装器,然后将其传递给模型或演示者。

它应该看起来像这样:

class ConnectionChecker(private val context: Context) {
val isOnline: Boolean
    get() {
        return try {
            val connectivityManager = context.getSystemService(
                    Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            connectivityManager.activeNetworkInfo != null &&
                    connectivityManager.activeNetworkInfo.isConnected
        } catch (exception: Exception) {
            false
        }
    }

}

Interactor 可以从您的数据库、Web 服务或任何其他数据源获取数据。 Interactor拿到数据后,会将数据发送给Presenter。因此,在您的 UI 中进行更改。您还可以将交互器放在 Presenter.

Context 是 MVP 中 Android View Layer 的一部分,因此 Presenter 不应该对此有任何想法,并且您不应将其传输到 PresenterInteractor.

您必须向 View 接口添加所需的方法并在 Android View 组件中实现它(例如, Activity 或片段)。