App中网络分层架构的设计实践

在新公司中担任架构师的职位后想对原有的app系统进行架构的重构。
先简单吐槽说一下原来App的架构,据说App的系统架构用的是MVC架构(我呵呵),懂的人都知道此时的我心里有几万头草泥马在奔腾了。
虽然我第一件做的事情是对系统进行分层和模块划分,但最近因为网络模块无法满足业务需求,我就同时对网络进行了设计。
新的网络模块的设计采用了3层的设计模式,从下到上分别是Api层、Service层、interface层,架构图如下(自己手绘的,还请见谅)。


image.png

下面分别介绍各层的作用,及代码描述语言

Api层

如图中所示,Api层承担的责任有
1、封装第三方网络库
2、实现post、get、upload等方法
3、实现cancel方法

class HTTPApi {
  HTTPApi getInstance() {
    //如果需要保管第三方的网络对象,这里可以实现一个单例
  }
  get(url, args, header, userAgent) {
    //调用第三方get方法
    return respData;
  }
  post(url, args, header, userAgent) {
    //调用第三方post方法
    return respData;
  }
}

Service层

如图中所示,Service层承担的责任有
1、设置公共参数
2、设置header、ua
3、初步解析数据并处理公共Error

class HTTPService {
  header() {
    return {
      "authentication": "133mfdmfldd",
      "Content-Type": "application/json",
      "X-timestamp": currentTimeMillis(),
      ...
    }
  }
  userAgent() {
    return "自定义的userAgent,一般是在系统ua后面加自己的内容";
  }
  static get(url, args, success, failure) {
    //args+公共参数
    resp = HTTPApi.instance.get(url, args, header(), userAgent());
    if (resp.code == "A000") {
      success(resp.data);
    } else if (resp.code == "A220") {
      //处理此公共错误
    } else if(resp.code == "B150") {
      //处理此公共错误
    } else {
      //返回业务错误
      failure(AppError(resp.code, resp.message));
    }
  }
  static post(url, args) {
    //args+公共参数
    resp = HTTPApi.instance.post(url, args, header(), userAgent());
    if (resp.code == "A000") {
      success(resp.data);
    } else if (resp.code == "A220") {
      //处理此公共错误
    } else if(resp.code == "B150") {
      //处理此公共错误
    } else {
      //返回业务错误
      failure(AppError(resp.code, resp.message));
    }
  }
}

Interface层

Interface层的责任比较简单,他主要是·对每个业务接口进行封装

class HTTPUserInterface {
  static getUrl(path) {
    if (kDebug) {
      return "http://debug-user.abc.com/" + path;
    } else {
      return "http://user.abc.com/" + path;
    }
  }
  static login(userName, password, success, failure) {
    Map args = {"userName": userName, "password": password};
    HTTPService.post(getUrl("account/login"), args, success, failure):
  }
  static getUserInfo(success, failure) {
    HTTPService.get(getUrl("account/userInfo"), null, success, failure);
  }
}
class HTTPMarketInterface {
  //基本同HTTPUserInterface
}
...

UI层

UI层即为用户能见到的界面,此层不属于网络层,但会调用Service层来获取数据

class LoginPage {
  //点击登录按钮后
  loginButtonClicked() {
    HTTPUserInterface.login("aprogram", "123456", (data) {
      _response = LoginModel.fromJson(data);
      //刷新页面,跳转页面
    }, (error) {
      Toast(error.message);
    });
  }
}

欢迎大家交流沟通

你可能感兴趣的:(App中网络分层架构的设计实践)