MVP——Model-View-Presenter
Model:用于数据的操作。
View:用于界面的显示与用户交互,在Android里面View通常就是Actvitiy、Fragment。
Presenter:是View跟Model的“中间人”,接收View的请求后,从Model获取数据交给View。
DEMO:
Model接口:
public interface IModel {
//返回数据,OnResultDataListener是监听器,监听数据操作是否成功(起到回调的作用)
void resultData(String str,OnResultDataListener resultDataListener);
}
OnResultDataListener接口:
public interface OnResultDataListener {
void onSuccess(String str);//数据返回成功
void onFail(String str);//数据返回失败
}
Model接口实现:
public class Model implements IModel{
@Override
public void resultData(String str, OnResultDataListener resultDataListener) {
if(str.equals("wzz")){//如果传来的数据str是“wzz”,则返回成功
resultDataListener.onSuccess(str+" 123 成功~");//OnResultDataListener起回调作用,将得到的数据进行返回
}else {
resultDataListener.onFail(str+" 123 失败~");
}
}
}
IView接口:
public interface IView {
void setData(String data);//显示数据到界面上
}
IView接口实现:
public class MainActivity extends Activity implements IView{
private IPresenter iPresenter;//*接口类名
private Button button;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.tv);
button = (Button) findViewById(R.id.bt);
iPresenter = new Presenter(this);//*重点:在此引入Presenter,把new Presenter的类赋给接口类
iPresenter.getDate("wzz1");//View 与 Presenter连接起来,向Presenter中传递数据
}
@Override
public void setData(String data) {//实现IView接口,在界面上显示数据
text.setText(data);
}
}
IPresenter接口:
public interface IPresenter {
void getDate(String msg);
}
IPresenter接口实现:
public class Presenter implements IPresenter, OnResultDataListener{//同时实现两个接口,将Presenter和Model连接
private IModel iModel;//*重点:在IPresenter中一定要引入IModel 接口类和IView 接口类
private IView iView;
public Presenter(IView iView){//*重点:实例化Presenter,将View引进来,并在此创建Model,实现三者的连接
this.iView = iView;
iModel = new Model();
}
@Override
public void getDate(String msg) {//实现IPresenter中的借口,view将数据传给Presenter ,Presenter 再传给Model
iModel.resultData(msg,this);
}
@Override
public void onSuccess(String str) {//Model接收数据,将数据处理完后,数据在次回调到Presenter,然后Presenter对界面进行更新
iView.setData(str);
}
@Override
public void onFail(String str) {
iView.setData(str);
}
}
网友评论