* Description:购物车逻辑层
*/
public class CartPresenter {
private CartModel cartModel;
private IcartView icartView;
public CartPresenter(IcartView icartView) {
cartModel =new CartModel();
attachView(icartView);
}
/**
* 绑定view到presenter
* @param icartView
*/
public void attachView(IcartView icartView){
this.icartView = icartView;
}
public void getCarts(HashMap<String,String> params,String url){
cartModel.getCarts(params, url, new CartModel.CartCallback() {
@Override
public void success(CartBean cartBean) {
if (icartView!=null){
icartView.success(cartBean);
}
}
@Override
public void fail(String msg) {
if (icartView!=null){
icartView.failure(msg);
}
}
});
}
/**
* 解除绑定,把view和presenter解绑,避免内存泄漏
*/
public void detachView(){
this.icartView = null;
}
}
VIEW
public interface IcartView {
void success(CartBean cartBean);//请求成功
void failure(String msg);//请求失败
}
Model
*/
public class CartModel {
Handler handler =new Handler();
/**
* 请求购物车数据
*
* @param params 参数
* @param url 请求url
*/
public void getCarts(HashMap<String, String> params, String url, final CartCallback cartCallback) {
OkHttpUtils.getInstance().postData(url, params, new RequestCallback() {
@Override
public void failure(Call call, IOException e) {
if (cartCallback != null) {
cartCallback.fail("网络有异常,请稍后再试");
}
}
@Override
public void onResponse(Call call, Response response) {
try {
String jsonResult = response.body().string();
if (!TextUtils.isEmpty(jsonResult)) {
parseResult(jsonResult, cartCallback);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
/**
* 解析购物车数据
*
* @param jsonResult
* @param cartCallback
*/
private void parseResult(String jsonResult, final CartCallback cartCallback) {
final CartBean cartBean = new Gson().fromJson(jsonResult, CartBean.class);
if (cartCallback != null && cartBean != null) {//代码规范,代码优化
handler.post(new Runnable() {
@Override
public void run() {
cartCallback.success(cartBean);
}
});
}
}
public interface CartCallback {
void success(CartBean cartBean);//回调bean对象给presenter
void fail(String msg);//异常信息回调
}
}