Android MVP 最优实现

概述

  1. Model:执行逻辑
  2. View:视图展示
  3. Presenter:业务处理
  4. Contract:当前view的契约者

Contract

契约者,相当于约束一个activity或者fragment使用的mvp中的具体哪些方法

public interface BaseContract {    interface Model {        void getVoid();            	boolean getBoolean();    }    interface IView  {                void onLoading();                      void onError(String throwable);		      	        void onSuccess(Object obj);    }    interface Presenter {        void getBoolean();      	      	void getVoid();    }}

Model

处理真正的逻辑的,传递进来的参数是已经处理好的参数,不需要去做除了业务之外的逻辑

public abstract class BaseModel implements BaseContract.Model{  		//没有返回值的逻辑    public void getVoid(){ 	       	//逻辑处理    }    	//返回boolea值的逻辑  	public boolean isBoolean(){    	//返回boolean值的逻辑      	//逻辑处理      return true;    }  	  	//加法  	public Integer add(int a, int b){    	return a + b;    }    	//将对象变成字符串  	public String getString(Object obj){    	return obj.toString();    }}

View

实现了view接口的具体实现类需要实现的方法,这些方法应该被实现类处理

public interface IBaseView extends BaseContract.IView{  	//显示错误信息    void onError(String errorStr);  	  	//处理成功逻辑  	void onSuccess(Object obj);    	//等待  	void onLoading();}

Presenter

业务处理,确保传递进model的参数的正确性。如果有错误,则需要传递进view,告诉view层

public class BasePresenter  implements BaseContract.Presenter{    protected IBaseView iBseView;//view    private BseMobel baseMobel;//mobel  	//构造方法传递进来实际实现IBseView接口的对象  	public BasePresenter(IBseView iView){    	iBseView = iView;      	baseModel = new BseModel();    }    	public void getVoid(){      	iBaseView.onLoading();    	baseModel.getVoid();	    }    	public void getBoolean(){      	iBaseView.onLoading();      if(baseModel.getBoolean()){      	iBseView.onSuccess();      }else{        iBseView.OnError("model处理了错误的结果");      }    }      //清除当前mvp对象    public void destory() {       iBseView = null;       baseMobel = null;    }} 

具体使用

public class MainActivity extends BaseMvpActivity<BasePresenter> implements BaseContract.IView {    @BindView(R.id.et_username_login)    TextInputEditText etUsernameLogin;    @BindView(R.id.et_password_login)    TextInputEditText etPasswordLogin;    @Override    public int getLayoutId() {        return R.layout.activity_main;    }    @Override    public void initView() {        mPresenter = new BasePresenter(this);    }   	@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // TODO: add setContentView(...) invocation        ButterKnife.bind(this);    }    @Override    public void onSuccess(Object bean) {        Toast.makeText(this, bean.getErrorMsg(), Toast.LENGTH_SHORT).show();    }    @Override    public void onLoading() {        ProgressDialog.getInstance().show(this);    }     @Override    public void onError(String throwable) {        Toast.makeText(this, throwable, Toast.LENGTH_SHORT).show();    }    }
发布了113 篇原创文章 · 获赞 48 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/yehui928186846/article/details/93629865
今日推荐