簡體   English   中英

如何在 Model View Presenter 模式中使用存儲庫模式和交互器模式?

[英]How do I use Repository pattern and Interactor pattern in a Model View Presenter pattern?

我正在 Model View Presenter 模式的幫助下開發應用程序。

我使用 Retrofit ,所以我有一個帶有端點的 ApiClient 和 ApiInterface 。 我在Repository class 中調用的RemoteDataSource class 中實現了接口。

我的問題是 - 如何使用交互器 class 使存儲庫與演示者通信?

到目前為止,這是我的代碼:

API接口

public interface ApiInterface {

@GET("?")
Call<ArrayList<Movie>> getMoviesByTitle(@Query("t") String title,@Query("apiKey") String apiKey);

}

遠程數據源 class

private static MovieRemoteDataSource instance;
private final ApiInterface service;

public MovieRemoteDataSource(ApiInterface movieApi) {
    service = ApiClient.createService(ApiInterface.class);
}

public static MovieRemoteDataSource getInstance(ApiInterface movieApi) {
    if (instance == null) {
        instance = new MovieRemoteDataSource(movieApi);
    }
    return instance;
}

@Override
public void getMovies(String title, String apiKey, final LoadMovieCallBack callback) {
    service.getMoviesByTitle(title,apiKey).enqueue(new Callback<ArrayList<Movie>>() {
        @Override
        public void onResponse(Call<ArrayList<Movie>> call, Response<ArrayList<Movie>> response) {
            ArrayList<Movie> movies = response.body();// != null ? //response.body().getTitle() : null;
            if (movies != null && !movies.isEmpty()) {
                callback.onMoviesLoaded(movies);
            } else {
                callback.onDataNotAvailable();
            }
        }

        @Override
        public void onFailure(Call<ArrayList<Movie>> call, Throwable t) {
            callback.onError();
        }
    });
}

帶有回調的 DataSource 接口

public interface MovieDataSource {
    interface LoadMovieCallBack{
        void onMoviesLoaded(ArrayList<Movie> movies);
        void onDataNotAvailable();
        void onError();

    }

    void getMovies(String title, String apiKey,LoadMovieCallBack callback);

}

存儲庫

 private MovieRemoteDataSource movieRemoteDataSource;


public MoviesRepository() {//ApiInterface movieApi) {
    //this.service = ApiClient.createService(ApiInterface.class);
}

public static MoviesRepository getInstance(ApiInterface service) {
    if (instance == null) {
        instance = new MoviesRepository();
    }
    return instance;
}





  public void getMovies(String title, String apiKey ) {
        movieRemoteDataSource.getMovies(title,apiKey,this);
    }

MoviesRepository ,您應該使用Callback聲明 function 。 您的Presenter應該實現MovieDataSource.LoadMovieCallBack並在您調用MoviesRepository時傳遞它

  public void getMovies(String title, String apiKey,MovieDataSource.LoadMovieCallBack callback) {
        movieRemoteDataSource.getMovies(title,apiKey,callback);
  }

是 Google MVP已經為 todo 應用示例完成的,您可以參考它。 但現在它已被棄用,因為 Google 推薦MVVM

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM