使用 Context 实现存储库模块

问题描述 投票:0回答:2

我想实现

Repository
模块来处理数据操作。我在
raw
目录中有 JSON 文件,想要创建具体的
Repository
实现来从文件中获取数据。我不确定是否可以在
Context
的构造函数或方法中使用
Repository
作为属性。

例如

public class UserRepository {

    UserRepository() {}

    public List<User> loadUserFromFile(Context contex) {
        return parseResource(context, R.raw.users);
    }
}
android repository-pattern android-architecture-components
2个回答
3
投票

恕我直言,您应该使用像 Dagger2 这样的 DI(依赖注入),为您提供

Context
之类的东西,

AppModule.class

@Module
public class AppModule {

    private Context context;

    public AppModule(@NonNull Context context) {
        this.context = context;
    }

    @Singleton
    @Provides
    @NonNull
    public Context provideContext(){
        return context;
    }

}

MyApplication.class

public class MyApplication extends Application {

    private static AppComponent appComponent;

    public static AppComponent getAppComponent() {
        return appComponent;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = buildComponent();
    }

    public AppComponent buildComponent(){
        return DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }
}

UserRepository.class

@Singleton
public class UserRepository {

    UserRepository() {}

    @Inject
    public List<User> loadUserFromFile(Context contex) {
        return parseResource(context, R.raw.users);
    }
}

快乐编码..!!


1
投票

我认为将上下文作为属性传递没有任何坏处。如果您不喜欢这个想法,那么您可以通过一种方便的方法检索上下文:Static way to get 'Context' on Android?

© www.soinside.com 2019 - 2024. All rights reserved.