Android之MVP框架入门

什么是MVP,为什么要用MVP?
网上介绍MVP的很多,百度一下你就知道,至于为什么要用MVP,当然是由于它的优势了:
1.代码简洁
此处的简洁是逻辑的简洁,而不是代码本身 举个栗子

image

比如购物车界面,有很多请求网络的地方:获取购物车商品列表、购物车商品的删除、购物车商品的购买等等, 这么多网络请求,如果都写在一个Activity,而且还有大量逻辑判断,那这个Activity的行数~ 看着就让人头痛, 即便写了注释,维护起来也是比较麻烦的
2.降低耦合,方便维护
MVP的使用,使Activity中的网络请求剥离出来 成为model、presenter,model只负责网络的请求、pesenter负责处理请求网络后的数据处理:加载中 成功 or 失败 取消加载;最后View进行界面的展示

整体的mvp结构图

image.png

Start:介绍一下BaseMvpActivity

MVP的Activity基类:纯粹的 MVP 包装,不要增加任何View层基础功能 如果要添加基类功能,建议写一个所有activity的基类添加

public abstract class BaseMvpActivity

extends Activity implements BaseView { protected P mPresenter; protected abstract P createPresenter(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter = createPresenter(); if (mPresenter == null) { throw new NullPointerException("Presenter is null! Do you return null in createPresenter()?"); } mPresenter.onMvpAttachView(this, savedInstanceState); } @Override protected void onStart() { super.onStart(); if (mPresenter != null) { mPresenter.onMvpStart(); } } @Override protected void onResume() { super.onResume(); if (mPresenter != null) { mPresenter.onMvpResume(); } } @Override protected void onPause() { super.onPause(); if (mPresenter != null) { mPresenter.onMvpPause(); } } @Override protected void onStop() { super.onStop(); if (mPresenter != null) { mPresenter.onMvpStop(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mPresenter != null) { mPresenter.onMvpSaveInstanceState(outState); } } @Override protected void onDestroy() { super.onDestroy(); if (mPresenter != null) { mPresenter.onMvpDetachView(false); mPresenter.onMvpDestroy(); } } }

在这里有人会觉得生命周期怎么会出现onMvpStart 或者onMvpResume等等
下面来解释一下MVP的生命周期:
就是为了定义P层生命周期与 V层同步

public interface IPresenter {

    void onMvpAttachView(V view, Bundle savedInstanceState);

    void onMvpStart();

    void onMvpResume();

    void onMvpPause();

    void onMvpStop();

    void onMvpSaveInstanceState(Bundle savedInstanceState);

    void onMvpDetachView(boolean retainInstance);

    void onMvpDestroy();
}

接下来 我们会用到WeakReference类从字面上了解 他的意思是弱引用

关于 弱引用,强引用、软引用、虚引用,可以参考
https://www.cnblogs.com/gudi/p/6403953.html

public class BasePresenter implements IPresenter {

    private WeakReference viewRef;

    protected V getView() {
        return viewRef.get();
    }

    protected boolean isViewAttached() {
        return viewRef != null && viewRef.get() != null;
    }

    private void attach(V view, Bundle savedInstanceState) {
        viewRef = new WeakReference(view);
    }

    @Override
    public void onMvpAttachView(V view, Bundle savedInstanceState) {
        attach(view, savedInstanceState);
    }

    @Override
    public void onMvpStart() {

    }

    @Override
    public void onMvpResume() {

    }

    @Override
    public void onMvpPause() {

    }

    @Override
    public void onMvpStop() {

    }

    @Override
    public void onMvpSaveInstanceState(Bundle savedInstanceState) {

    }

    private void _detach(boolean retainInstance) {
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }

    @Override
    public void onMvpDetachView(boolean retainInstance) {
        _detach(retainInstance);
    }

    @Override
    public void onMvpDestroy() {

    }
}

接下来就是 view和model绑定处理数据


public class MainPresenterImpl extends BasePresenter implements MainContract.IMainPresenter {
    private LoginMobel mMobel;

    public MainPresenterImpl() {
        mMobel = new LoginMobel();
    }


    @Override
    public void main(String username, String password, String token) {
        //先进行非空判断
        if (isViewAttached()) {
            handleLogin(getView(), username, password, token);
        }
    }

    @Override
    public void login(String username, String password, String token) {
        //先进行非空判断
        if (isViewAttached()) {
         Login(getView(), username, password, token);
        }
    }

    private void Login(final MainContract.IMainView view, String username, String password, String token) {
        mMobel.login(username, password, token, new StringCallbackAdapter() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                view.loginSuccess();
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                view.loginFailed(response);
            }
        });
    }


    private void handleLogin(final MainContract.IMainView view, String username, String password, String token) {
        mMobel.login(username, password, token, new StringCallbackAdapter() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                view.mainSuccess();
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                view.mainFailed(response);
            }
        });
    }
}

使用

public class MainActivity extends BaseMvpActivity implements MainContract.IMainView {
  @Override
    protected MainContract.IMainPresenter createPresenter() {
        return new MainPresenterImpl();
    }

 mPresenter.main(username, password, token);

  @Override
    public void mainSuccess() {
        Toast.makeText(this, "mainSuccess", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void mainFailed(String msg) {
        Toast.makeText(this, "mainFailed", Toast.LENGTH_SHORT).show();
    }

时间有限,暂时就先这样,具体可下载Demo查看 ↓

本Demo:https://gitee.com/oubajunping/androidzhimvprumen
MVP快速生成类的插件: https://github.com/githubwing/MVPHelper

你可能感兴趣的:(Android之MVP框架入门)