mvp封装

2019-01-24  本文已影响0人  Android纯白

什么是mvp,我就不多说,mvp作用就是用一个类作为桥梁,然后进行数据和view的一些交互。通过接口进行相互交流。
mvp主要是由3部分组成(view,presenter,model),这里封装我舍弃了model,数据处理直接放在presenter上,然后通过接口实现了ui和view的交互(原本的交互是放在presenter上处理)

创建view接口类和presenter接口类(model接口类)

//view的接口类
 public interface BaseView {
    Context getContext();
}

//presenter
public interface BasePresenter<V extends BaseView>  {
    //添加view
    void addView(V view);
   //删除view
    void deleteView();
}

实现presenter接口

-通过addview拿到view的对象,

public class PresenterImp<V extends BaseView> implements BasePresenter<V> {
    protected V mView;
    private WeakReference<V> vWeakReference;
    @Override
    public void addView(V view) {
        vWeakReference = new WeakReference<>(view);
        mView=vWeakReference.get();
    }
    @Override
    public void deleteView() {
        if (vWeakReference!=null)
        {
            vWeakReference.clear();
            mView=null;
        }
    }
}

实现BaseView接口

public abstract class MvpActivity<DB extends ViewDataBinding,P extends PresenterImp>
        extends BaseActivity<DB> implements BaseView {

    protected P mPresenter;
    @Override
    public Context getContext() {
        return this;
    }

    //创建PresenterImp对象
    protected abstract P creartPresenter();

    @Override
    protected void beforeView() {
        super.beforeView();
        mPresenter= creartPresenter();
        if (mPresenter!=null) {
            mPresenter.addView(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter!=null) {
            mPresenter.deleteView();
        }
    }
}

举栗子

//接口管理类
public class GuideContract {
    interface View extends BaseView
    {

    }

    interface Presenter extends BasePresenter<View>
    {

    }
}

//数据类
public class GuidePresenter extends PresenterImp<GuideContract.View> implements GuideContract.Presenter{

}

//ui类
public class GuideActivity extends MvpActivity<ActivityGuideBinding,GuidePresenter>
        implements GuideContract.View{}
上一篇下一篇

猜你喜欢

热点阅读