《MainView 》
public interface MainView {
void success(int type, String data);//type 做为区分 是哪个请求
void fail(int type, String error);
1
2
3
}
《MainModel 》
public interface MainModel {
interface OnCallBackListener {
void success(int type, String data);//type 做为区分 是哪个请求
void fail(int type, String error);
}
void doShopCar(int type, String url, OnCallBackListener listener);
1
2
3
4
5
6
7
}
《MainModelIml 》
public class MainModelIml implements MainModel {
private OnCallBackListener listener;
private int type;
@Override
public void doShopCar(int type, String url, OnCallBackListener listener) {
this.listener = listener;
this.type = type;
//请求购物车数据
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
final Message message = Message.obtain();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
message.what = 1001;
message.obj = e.getMessage();
handler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
message.what = 1000;
message.obj = response.body().string();
handler.sendMessage(message);
}
});
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1000) {//成功
String data = (String) msg.obj;
listener.success(type, data);
} else {
//失败
String error = (String) msg.obj;
listener.success(type, error);
}
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
}
《MainPresenter 》
public interface MainPresenter {
void doShopCar(int type, String url);
1
}
《MainPresenterIml 》
public class MainPresenterIml implements MainPresenter, MainModel.OnCallBackListener {
private MainModel mainModel;
private MainView mainView;
public MainPresenterIml(MainModel mainModel, MainView mainView) {
this.mainModel = mainModel;
this.mainView = mainView;
}
@Override
public void doShopCar(int type, String url) {
mainModel.doShopCar(type, url, this);
}
@Override
public void success(int type, String data) {
mainView.success(type, data);
}
@Override
public void fail(int type, String error) {
mainView.fail(type, error);
}
//销毁
public void destory() {
if (mainView != null) {
mainView = null;
}
if (mainModel != null) {
mainModel = null;
}
System.gc();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
}
---------------------
【转载,仅作分享,侵删】
作者:偏执青年
原文:https://blog.csdn.net/weixin_44666694/article/details/89059339
版权声明:本文为博主原创文章,转载请附上博文链接!
|
|