郴州市兴旺宝明通网络有限公司
首页 | 联系方式 | 加入收藏 | 设为首页 | 手机站

产品目录

联系方式

联系人:业务部
电话: 00144-186681728
邮箱:service@tjzhuojun.com

当前位置:首页 >> 新闻中心 >> 正文

Android网络框架二(设计模式)

字号:
摘要:Android网络框架二(设计模式)

结合上一篇
Android网络框架必备的功能
在描述了大体功能,现在关心的代码就是它里面的设计模式

OkHttpUtil{
 /**
 * 同步请求
 * @param info 请求信息体
 * @return HttpInfo
 */
 @Override
 public HttpInfo doSync(HttpInfo info) {
 return OkHttpHelper.Builder()
 .httpInfo(info)
 .requestType(info.getRequestType())
 .helperInfo(packageHelperInfo(info))
 .build()
 .doRequestSync();
 }
}
/**
 * OkHttpUtil业务类:负责处理所有业务
 * @author zhousf
 */
public class OkHttpHelper {
public static final class Builder {
 ...
 public Builder() {
 }
 public OkHttpHelper build(){
 if(!this.uploadFileInfoList.isEmpty()){
 this.businessType = BusinessType.UploadFile;//文件上传
 UploadFileInfo uploadFileInfo = uploadFileInfoList.get(0);
 if(!TextUtils.isEmpty(uploadFileInfo.getUrl())){
 this.httpInfo.setUrl(uploadFileInfo.getUrl());
 }
 } else if(downloadFileInfo != null){
 this.businessType = BusinessType.DownloadFile;//文件下载
 if(!TextUtils.isEmpty(downloadFileInfo.getUrl())){
 this.httpInfo.setUrl(downloadFileInfo.getUrl());
 }
 } else{
 this.businessType = BusinessType.HttpOrHttps;//http/https请求
 }
 return new OkHttpHelper(this);
 }
 public Builder httpInfo(HttpInfo httpInfo){
 this.httpInfo = httpInfo;
 return this;
 }
 public Builder helperInfo(HelperInfo helperInfo){
 this.helperInfo = helperInfo;
 return this;
 }
 public Builder downloadFileInfo(DownloadFileInfo downloadFileInfo){
 this.downloadFileInfo = downloadFileInfo;
 return this;
 }
 public Builder uploadFileInfo(UploadFileInfo uploadFileInfo){
 uploadFileInfoList.add(uploadFileInfo);
 return this;
 }
 public Builder uploadFileInfoList(List<UploadFileInfo> uploadFiles){
 uploadFileInfoList.addAll(uploadFiles);
 return this;
 }
 public Builder clientBuilder(OkHttpClient.Builder clientBuilder){
 this.clientBuilder = clientBuilder;
 return this;
 }
 public Builder requestType(@RequestType int requestType){
 this.requestType = requestType;
 return this;
 }
 public Builder callback(BaseCallback callback){
 this.callback = callback;
 return this;
 }
 public Builder progressCallback(ProgressCallback progressCallback){
 this.progressCallback = progressCallback;
 return this;
 }
 }
}

在OkHttpHelper中 的静态内部类Builder中给成员变量赋值后,然后返回Builder类本身的方式,然后在调用时只需要通过追加的方式,从而达到连续给不同的成员变量赋值的效果,这种设计模式,可以在以后尝试下。
在这里设定了httpInfo,requestType,HelperInfo
之后的build方法则是根据设定的内容,来判断当前的业务类型,是上传文件,是下载文件,还是http或者https请求,同时把父类对象OkHttpHelper实例化出来然后最后一步就通过`

public HttpInfo doRequestSync(){
 return httpHelper.doRequestSync(this);
 }
 public void doRequestAsync(){
 httpHelper.doRequestAsync(this);
 }
 public void downloadFile(){
 downUpLoadHelper.downloadFile(this);
 }
 public void uploadFile(){
 downUpLoadHelper.uploadFile(this);
 }

于是,流程从OkHttpHelper移动到了 HttpHelper或者DownUpLoadHelper中
介绍了这么多,可能下一篇文章才能看到最终的底层实现