您的位置:首页 > 运维架构 > 网站架构

安卓开发 第五篇 我的安卓应用架构设计-----Repository类

2016-05-04 22:51 561 查看
Repository类被我放在项目架构中的领域层中(domain), 在我的项目架构中充当的是数据仓库的角色,所有需要的数据都从Repository获取。

先看看所有Repository的基类:

/**
* BaseRepository app的数据仓库类的基类,所有Repository类都直接或者间接继承自它
* <p/>
* Created by tianlai on 16-3-3.
*/

public abstract class BaseRepository<S> {
private static final String TAG="repository";

protected Retrofit retrofit;

protected static User user;  //用户信息

protected Context mContext;//Context对象,用来判断网络连接

private boolean isCancle=false;

protected S service;

public BaseRepository(Context context, Retrofit retrofit) {
this.mContext = context;
this.retrofit = retrofit;

service=retrofit.create(getServiceClass());
}

/**
* 获取网络接口类型
*
* @return
*/
protected abstract Class<S> getServiceClass();

/**
* 获取用户的信息
*
* @return
*/
public static User getUser() {
return user;
}

/**
* 设置用户的信息
*
* @param user
*/
public static void setUser(User user) {
BaseRepository.user = user;
}

/**
* 检查是否可以进行网络请求
*
* @return
*/
public boolean isCanRequest() {
//验证用户
if (user == null || user.id() == 0) {
ToastUtil.showToast(mContext, "用户为空,请重新登录");

return false;
}

//验证网络连接
if (!AppUtil.isOnline(mContext)) {
ToastUtil.showToast(mContext, "请检查你的网络连接");

return false;
}

return true;
}

/**
* 判断请求是否取消
*
* @return
*/
public boolean isCancled() {

LogUtil.d(TAG, "请求是否取消:" + isCancle);

return isCancle;
}

/**
* 取消请求
*/
public void cancleRequest() {
this.isCancle = true;
}

/**
* 开始请求
*/
public void startRequest() {
if(!isCanRequest){
cancleRequest();
return;
}
this.isCancle = false;
}

}


下面来看看如何使用的:(登录的数据仓库)

/**
* LoginRepository 登录的数据仓库类
* <p/>
* Created by tianlai on 16-3-16.
*/
public class LoginRepository extends BaseRepository<LoginApiService> {

@Inject
public LoginRepository(Context context, Retrofit retrofit) {
super(context, retrofit);
}

@Override
protected Class<LoginApiService> getServiceClass() {
return LoginApiService.class;
}

/**
* 登录请求
*
* @param mobile
* @param psw
* @return
*/
public rx.Observable<LoginResponce> login(@NonNull String mobile, @NonNull String psw) {

startRequest();

return service.login(mobile,psw);
}
}


其中:

LoginApiService是登录的接口,网络请求使用的是retrofit;

LoginResponce是登录的直接返回结果类

由于目前项目中数据量比较小,数据更新比较频繁,暂时未做缓存处理,如果以后有需要做缓存处理,那么缓存处理也会放在Repository中,需要自定义一些缓存策略。

好了就说到这里吧!

如果有更深的理解,本文将会修改;

如果有错误的地方,欢迎指正;

如果你有更好的理解,欢迎交流。

本文为原创文章,版权归博主所有,转载请注明出处。

更多资料:

我的github地址以及使用demo: https://github.com/naivor/naivorapp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: