前言
因项目需要,初识了MVP模式,但也只是大致知道它是干什么的,因此接下来就简单分析一下,加深印象的同时,能进一步搞清楚它到底是干什么的。
概念
MVP 全称:Model-View-Presenter ;Presenter负责逻辑的处理,Model提供数据,View负责显示。
上代码
先分别定义一个BaseView ,BaseModel ,BasePresenter
BaseView
public interface BaseView {
void showMsg(String msg);
}
BaseModel
public interface BaseModel {
}
BasePresenter
public abstract class BasePresenter<M, T> {
public Context context;
public M mModel;
public T mView;
public RxManager mRxManager = new RxManager();
public void setVM(T v, M m) {
this.mView = v;
this.mModel = m;
this.onStart();
}
public abstract void onStart();
public void onDestroy() {
mRxManager.clear();
}
}
接下来定义一个负责协调调用Presenter,Model,View的类MyListContract
public class MyListContract {
//负责为页面加载数据
interface View extends BaseView {
/**
* 获取
*/
void getList();
/**
* 加载
*/
void loadList(List<ListBean> myList);
}
interface Model extends BaseModel {
//负责调用接口,获取相应数据
Observable<BaseResEntity<List<ListBean>>> requstMyList();
}
abstract static class Presenter extends BasePresenter<Model, View> {
public abstract void getMyList();
@Override
public void onStart() {
}
}
}
接下来实例化真正属于MyListContract的MyListModel,MyListPresenter
MyListModel
public class MyListModel implements MyListContract.Model{
@Override
public Observable<BaseResEntity<List<ListBean>>> requstMyList() {
//此处添加具体的请求数据方法
}
}
MyListPresenter
public class MyListPresenter extends MyListContract.Presenter{
@Override
public void getMyList() {
mRxManager.add(mModel.requstMyList().subscribe(response -> {
if (response.isSuccess()) {
List<ListBean> mList = response.getData();
mView.loadList(mList);
} else {
mView.showMsg("加载列表失败");
}
}, error -> {
}));
}
}
最后在相应activity中,实例化View的方法,在需要使用的时候调用即可
@Override
public void getList() {
mPresenter.getMyList();
}
@Override
public void loadList(List<ListBean> mList) {
Log.i("success", "loadList " + mList);
}
大致就是这样,That's all !Thank you~
网友评论