如何以MVP模式将上下文传递到存储库

Tah*_*ani 6 performance android android-layout android-fragments android-mvp

我一直在学习和整合MVP pattern,很少有问题。

我从这张图中了解到的是

活动将创建的实例Presenter,并将其引用和model对象传递给演示者

MainPresenter mainPresenter = new MainPresenter(this, new MainModel());
Run Code Online (Sandbox Code Playgroud)

接下来,如果演示者需要从本地首选项或远程存储或获取任何数据,它将询问模型。

然后模型将询问存储库以存储和检索数据。

在此处输入图片说明

我遵循了一些教程,这就是我实现模式的方式。

接口

public interface MainActivityMVP {

    public interface Model{

    }

    public interface View{
        boolean isPnTokenRegistered();
    }

    public interface Presenter{

    }
}
Run Code Online (Sandbox Code Playgroud)

活动

MainPresenter mainPresenter = new MainPresenter(this, new MainModel());
mainPresenter.sendDataToServer();
Run Code Online (Sandbox Code Playgroud)

主持人

public void sendDataToServer() {

    //  Here i need to ask `model` to check 
        do network operation and save data in preference
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是我需要访问上下文sharedPreference,但是我没有经过context任何地方。我也不想使用static context。我想知道将上下文传递到MVP模式的正确方法。

Lev*_*ira 2

好吧,最好的方法是将您的首选项类包装在辅助类中,并使用Dagger将其注入到您需要的任何地方,这样您的演示者/模型就不需要了解上下文。例如,我有一个提供各种单例的应用程序模块,其中之一是我的 Preferences Util 类,用于处理共享首选项。

@Provides
@Singleton
public PreferencesUtil providesPreferences(Application application) {
    return new PreferencesUtil(application);
}
Run Code Online (Sandbox Code Playgroud)

现在,每当我想使用它时,我只需 @Inject 它:

@Inject
PreferencesUtil prefs;
Run Code Online (Sandbox Code Playgroud)

我认为学习曲线是值得的,因为您的 MVP 项目将更加解耦。

但是,如果您愿意忘记“演示者不了解 Android 上下文”规则,您可以简单地将 getContext 方法添加到视图界面并从视图中获取上下文:

public interface MainActivityMVP {

    public interface Model{

    }

    public interface View{
        boolean isPnTokenRegistered();
        Context getContext();
    }

    public interface Presenter{

    }
}
Run Code Online (Sandbox Code Playgroud)

进而:

public void sendDataToServer() {
      Context context = view.getContext();
}
Run Code Online (Sandbox Code Playgroud)

我见过一些人这样实现 MVP,但我个人更喜欢使用 Dagger。

您还可以按照评论中的建议使用应用程序上下文。