MVP实战_1

演示效果:

MVP设计模式演示.gif

这里的演示效果是利用TabLayout+ViewPager+Fragment完成的,由于本篇文章不是讲具体实现,所以和MVP思想不相关的具体实现代码我会忽略一部分。

前言

MVP开发模式,算是老生常谈的话题了,最近一段时间也比较热门,网上相关的资料不少,这里就不再做重复的描述。
这里谈一下个人的一些理解:


mvc模式.png

由于Android平台的特殊性,从MVC的角度来讲,XML布局文件作为视图层(V),Activity作为控制层(C),一些具体的业务操作,如读写数据库,网络访问等作为业务逻辑层(M),单纯的XML布局又不能满足V层的需要,例如我们需要对一个控件进行动态的隐藏和显示,这点单纯的XML是办不到的,此时我们只能在Activity里去做实现了,这样子下来,使得Activity既是V又是C,随着业务的扩展,代码逻辑也渐渐变得复杂起来,加上MVC模式的设计,Model层和View层又是直接交互的,导致Activity的职责会变得很重,慢慢的变得臃肿不堪,不易扩展,更不要提测试了。

mvp模式.png

既然有问题的存在,自然就有解决问题的办法,此时MVP出现了,在我看来MVP模式其实就是从并不标准的MVC模式演化而来的,它减轻了Activity的职责,简化了Activity的代码,把复杂的逻辑交给了P层来处理,较低了系统的耦合度,更加方便了测试。

这样的开发模式下来,也使得各层的职责更加单一了,V层只关心用户的输入请求动作,P层相当于V层和M层的“信使”只关心转发数据,来自V层的请求数据,来自M层的响应数据,而M层则只需要关心的具体的业务逻辑操作即可。

言归正传

说了这么多,来点实战吧,这里我演示一个比较常见的功能,列表的下拉刷新和上拉加载数据。

所涉及的开源框架:
网络加载框架:Retrofit
图片加载框架:Picasso
响应式编程框架:Rxjava
注解框架:ButterKnife
带有下拉刷新,上拉加载的RecyclerView:XRecyclerView
JSON数据的解析:Gson

数据来源

http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1

这里的来源是来自GANK.IO的福利妹纸图,然后利用GsonFormat生成JavaBean,代码太长我就不贴了。

关于基类

View层
/** * 基类View接口 
* Created by chenwei.li 
* Date: 2016-01-11
* Time: 00:22 
*/
public interface IBaseView {   
  void showLoadingDialog();  
  void cancelLoadingDialog();   
  void showErrorMsg(String errorMsg);
}

这个基础View接口需要让每个具体的业务View都去继承实现,里面封装了一些常用的方法,例如我们在加载数据的时候都为了良好的用户体验,都需要显示进度条,或者弹出对话框来提醒用户正在进行,当数据加载完毕都需要关闭这个提醒,当加载出错的时候,需要提醒用户出错信息。

/**
 * 基类Fragment
 * Created by chenwei.li
 * Date: 2016-01-03
 * Time: 23:52
 */
public abstract class BaseFragment extends Fragment implements IBaseFragment {

    //当前Fragment视图对象
    protected View mView;


    /**
     * Activity对象,避免getActivity()出现null
     */
    protected Activity mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        /**
         * 绑定视图
         */
        if (mView == null) {
            mView = inflater.inflate(bindLayout(), container, false);
        }
        /**
         * 依赖注入
         */
        ButterKnife.bind(this, mView);

        /**
         * 创建Fragment
         */
        createFragment(savedInstanceState);

        /**
         * 初始化视图,默认值
         */
        initView();
        /**
         * 获取对应数据(网络,数据库)
         */
        getData();

        return mView;
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        /**
         * 解绑ButterKnife
         */
        ButterKnife.unbind(this);

    }
}
/**
 * 基类Fragment(懒加载)
 * Create by: chenwei.li
 * Date: 2016-05-26
 * time: 09:15
 * Email: lichenwei.me@foxmail.com
 */
public abstract class BaseLazyFragment extends Fragment implements IBaseFragment {


    //当前Fragment视图对象
    protected View mView;

    /**
     * 是否加载布局
     */
    protected boolean isPrepare;

    /**
     * 是否显示布局
     */
    protected boolean isVisiable;

    /**
     * 是否是第一次加载
     */
    protected boolean isFirst;


    /**
     * Activity对象,避免getActivity()出现null
     */
    protected Activity mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        /**
         * 绑定视图
         */
        if (mView == null) {
            mView = inflater.inflate(bindLayout(), container, false);
            isPrepare = true;
            isFirst = true;
        }

        /**
         * 依赖注入
         */
        ButterKnife.bind(this, mView);

        /**
         * 创建Fragment
         */
        createFragment(savedInstanceState);

        /**
         * 初始化视图,默认值
         */
        initView();

        return mView;
    }

    /**
     * 判断当前Fragment是否已经显示
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisiable = true;
            onVisible();
        } else {
            isVisiable = false;
        }
    }

    protected void onVisible() {
        lazy();
    }

    /**
     * 要进行懒加载的数据
     */
    protected void lazy() {
        if (isPrepare && isVisiable && isFirst) {
            lazyLoadData();
            isFirst = false;
        }
    }

    /**
     * 需要进行懒加载的数据
     */
    protected abstract void lazyLoadData();


    /**
     * 只需要空实现,所有的懒加载数据都在lazyLoadData里面执行
     */
    @Override
    public void getData() {
    }
}


上面是基础类BaseFragment的封装,实现了IBaseFragment接口里的方法,代码并不复杂,大家根据注释看下就可以理解了,这里因为我的注入框架用的ButterKnife,所以在创建Frgament的时候,我去绑定了View,当Fragment销毁的时候,去取消绑定。
这里根据具体业务,我又多封装了一个具有懒加载功能的Fragment,这个LazyBaseFragment和普通的Fragment区别在于,当我们使用ViewPager去嵌套Fragment的时候,由于ViewPaer的原因,默认它会加载当前页面的左右各一个页卡,有时候用户需要看当前页面并不执行滑动操作去看其他的,但是程序已经加载了页面,势必会造成一些资源浪费,所以我根据setUserVisibleHint(boolean isVisibleToUser)和标志位的判断,来确定在页面加载且用户滑到当前页的时候才去加载数据的。这点的想法起源来自简书的APP,大家看下图就能明白:

简书APP
简书APP

很明显,简书也运动了Fragment的懒加载,这里可能有朋友会说关于ViewPager里的setOffscreenPageLimit(int pgaeSize)方法,这个方法的作用是控制ViewPager保留当前页面的左右各几个页面的数据状态,而不让它进行滑动销毁,也可以决定ViewPager一次性加载几个页卡,所以把它设置为0不就解决了,其实不是的,如果你用去看过ViewPager的源码,你就会发现这样的一段代码:

    /**
     * Set the number of pages that should be retained to either side of the
     * current page in the view hierarchy in an idle state. Pages beyond this
     * limit will be recreated from the adapter when needed.
     *
     * <p>This is offered as an optimization. If you know in advance the number
     * of pages you will need to support or have lazy-loading mechanisms in place
     * on your pages, tweaking this setting can have benefits in perceived smoothness
     * of paging animations and interaction. If you have a small number of pages (3-4)
     * that you can keep active all at once, less time will be spent in layout for
     * newly created view subtrees as the user pages back and forth.</p>
     *
     * <p>You should keep this limit low, especially if your pages have complex layouts.
     * This setting defaults to 1.</p>
     *
     * @param limit How many pages will be kept offscreen in an idle state.
     */
    public void setOffscreenPageLimit(int limit) {
        if (limit < DEFAULT_OFFSCREEN_PAGES) {
            Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
                    DEFAULT_OFFSCREEN_PAGES);
            limit = DEFAULT_OFFSCREEN_PAGES;
        }
        if (limit != mOffscreenPageLimit) {
            mOffscreenPageLimit = limit;
            populate();
        }
    }

而这里的

private static final int DEFAULT_OFFSCREEN_PAGES = 1;

所以不管你是设置0,或者更小的数,默认它都是为1的,也就是默认加载3个页卡,保留当前页卡的左右页卡状态。

Presenter层
/**
 * 基类Presenter接口
 * Create by: chenwei.li
 * Date: 2016-05-31
 * time: 14:25
 * Email: lichenwei.me@foxmail.com
 */
public interface IBasePresenter<V extends IBaseView> {

    /**
     * V层注入引用
     * @param mvpView
     */
    void attachView(V mvpView);

    /**
     * 销毁V层引用
     */
    void detachView();

}

这里封装了2个方法,用来使View层的Activity和Fragment和P层的生命状态保持一致,当页面销毁的时候,这次Context上下文的引用也就没有理由存在了,这里我们把它置为null,便于GC回收。

/**
 * 基类BasePresenter
 * Create by: chenwei.li
 * Date: 2016-05-31
 * time: 11:14
 * Email: lichenwei.me@foxmail.com
 */
public class BasePresenter<T extends IBaseView> implements IBasePresenter<T> {

    private T mMvpView;

    @Override
    public void attachView(T mvpView) {
        this.mMvpView = mvpView;
    }

    @Override
    public void detachView() {
        this.mMvpView = null;
    }

    public T getMvpView() {
        return mMvpView;
    }
}

基类Presenter,让所有的P层继承。

具体代码

View层

/**
 * View层妹纸福利
 * Create by: chenwei.li
 * Date: 2016-05-26
 * time: 22:06
 * Email: lichenwei.me@foxmail.com
 */
public interface IWealView extends IBaseView {

    void getWealList(int pageSize, int currentPage);

    void onRefreshData(List<WealEntity.ResultsBean> resultsBean);

    void onLoadMoreData(List<WealEntity.ResultsBean> resultsBean);

}

这里提供了操作接口,因为在本页面的业务只是单纯的加载列表数据,刷新数据,所以这里定义了3个方法,用来满足业务。

/**
 * 福利Fragment
 * Create by: chenwei.li
 * Date: 2016-05-25
 * time: 11:19
 * Email: lichenwei.me@foxmail.com
 */
public class WealFragment extends BaseLazyFragment implements IWealView {


    @Bind(R.id.rv_wealView)
    XRecyclerView mRvWealView;


    //福利适配器与数据源
    private WealAdapter mWealAdapter;
    private List<WealEntity.ResultsBean> mResultsBeans;

    //福利P层
    private WealPresenter mWealPresenter;

    //记录当前页数,默认为1
    private int mCurrentPage = 1;


    /**
     * 懒加载数据
     */
    @Override
    protected void lazyLoadData() {
        getWealList(10, mCurrentPage);
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_weal;
    }

    @Override
    public void createFragment(Bundle savedInstanceState) {
    }



    @Override
    public void initView() {

        //注入P层
        mWealPresenter = new WealPresenter();
        mWealPresenter.attachView(this);

        //创建数据源,设置适配器
        mResultsBeans = new ArrayList<WealEntity.ResultsBean>();
        mWealAdapter = new WealAdapter(mResultsBeans);
        mRvWealView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRvWealView.setAdapter(mWealAdapter);

        //设置动画,刷新样式
        mRvWealView.setItemAnimator(new DefaultItemAnimator());
        mRvWealView.setArrowImageView(R.drawable.iconfont_downgrey);

        //监听刷新数据
        mRvWealView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                getWealList(10, mCurrentPage);
            }

            @Override
            public void onLoadMore() {
                getWealList(10, mCurrentPage);
            }
        });


    }


    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void cancelLoadingDialog() {

    }

    /**
     * 显示错误信息
     *
     * @param errorMsg
     */
    @Override
    public void showErrorMsg(String errorMsg) {
        ToastUtil.showShort(MyApplication.getContext(), errorMsg);
    }

    /**
     * 获取数据
     *
     * @param pageSize
     * @param currentPage
     */
    @Override
    public void getWealList(int pageSize, int currentPage) {
        mWealPresenter.getWealList(pageSize, currentPage);
        mCurrentPage++;
    }


    /**
     * 下拉刷新数据回调
     * @param resultsBean
     */
    @Override
    public void onRefreshData(List<WealEntity.ResultsBean> resultsBean) {
        mResultsBeans.clear();
        mResultsBeans.addAll(resultsBean);
        mWealAdapter.notifyDataSetChanged();
        mRvWealView.refreshComplete();
    }

    /**
     * 上拉加载数据回调
     * @param resultsBean
     */
    @Override
    public void onLoadMoreData(List<WealEntity.ResultsBean> resultsBean) {
        mResultsBeans.addAll(resultsBean);
        mWealAdapter.notifyDataSetChanged();
        mRvWealView.loadMoreComplete();
        if (resultsBean.size() < 10) {
            //当加载新数据的条数不足10条,则关闭上拉加载
            mRvWealView.setLoadingMoreEnabled(false);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mWealPresenter.detachView();
    }


}

这里采用了懒加载LazyFragment,当页面加载完毕且用户当前界面处于它的时候,会调用执行lazyData加载数据,当下拉刷新,上拉加载的时候会对应的执行方法,且改变当前页码。这里在页面初始化加载和销毁的时候,分别去调用了P层的注入和销毁方法,用来保存生命状态一致。

Presenter层

/**
 * 获取福利Presenter层
 * Create by: chenwei.li
 * Date: 2016-05-26
 * time: 22:20
 * Email: lichenwei.me@foxmail.com
 */
public class WealPresenter extends BasePresenter<IWealView> {

    private IWealModel iWealModel = new WealModel();


    @Override
    public void attachView(IWealView mvpView) {
        super.attachView(mvpView);
    }


    @Override
    public void detachView() {
        super.detachView();
    }

    /**
     * 根据加载数量和页码加载数据
     *
     * @param pageSize
     * @param currentPage
     */
    public void getWealList(int pageSize, final int currentPage) {
        iWealModel.getWealList(pageSize, currentPage, new Subscriber<WealEntity>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                getMvpView().showErrorMsg(e.getMessage());
            }

            @Override
            public void onNext(WealEntity wealEntity) {
                if (wealEntity.getResults() != null) {
                    if (currentPage == 1) {
                        getMvpView().onRefreshData(wealEntity.getResults());
                    } else {
                        getMvpView().onLoadMoreData(wealEntity.getResults());
                    }

                }
            }
        });

    }

}

这里没什么好说的,只是作为“信使”,传递了View层的请求给Model层,并通过Rxjava的订阅回调对应的方法,再次传递数据给View层。

Model层

/**
 * 网络接口包装类
 * Create by: chenwei.li
 * Date: 2016-05-23
 * time: 00:43
 * Email: lichenwei.me@foxmail.com
 */
public class RetrofitWapper {

    private static RetrofitWapper mRetrofitWapper;
    private Retrofit mRetrofit;

    /**
     * 将构造函数私有化
     */
    private RetrofitWapper() {
        mRetrofit = new Retrofit.Builder().baseUrl(Constant.BASE_URL).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
    }

    /**
     * 获取RetrofitWapper实例(单例模式)
     *
     * @return
     */
    public static RetrofitWapper getRetrofitWapperInstance() {
        if (mRetrofitWapper == null) {
            synchronized (RetrofitWapper.class) {
            mRetrofitWapper = new RetrofitWapper();
        }
    }
        return mRetrofitWapper;
    }

    /**
     * 创建接口访问入口
     * @param service
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service) {
        return mRetrofit.create(service);
    }


    public class Constant {
        public static final String BASE_URL = "http://gank.io/api/";
    }

}

这里写了一个帮助类,用来提供Retrofit的实例(单例),由于Retrofit底层默认是提供Okhttp支持的,所以如果这里要对Okhttp进行个性化定制也是很容易的,例如:

    private RetrofitWapper() {
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        okHttpClient.connectTimeout(5, TimeUnit.SECONDS);
        mRetrofit = new Retrofit.Builder().client(okHttpClient.build()).baseUrl(Constant.BASE_URL).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
    }

再来看下Retrofit的service:

/**
 * Gank.io接口类
 * Create by: chenwei.li
 * Date: 2016-05-26
 * time: 16:11
 * Email: lichenwei.me@foxmail.com
 */
public interface GankApiService {

    /**
     * 获取福利列表
     *
     * @param pageSize
     * @param currentPage
     * @return
     */
    @GET("data/福利/{pageSize}/{currentPage}")
    Observable<WealEntity> getWealList(@Path("pageSize") int pageSize, @Path("currentPage") int currentPage);
}

Model层的业务接口及实现:

/**
 * 获取福利Model层接口
 * Create by: chenwei.li
 * Date: 2016-05-26
 * time: 22:31
 * Email: lichenwei.me@foxmail.com
 */
public interface IWealModel {
     void getWealList(int pageSize,int currentSize, Subscriber<WealEntity> wealEntitySubscriber);
}

/**
 * Create by: chenwei.li
 * Date: 2016-05-26
 * time: 22:28
 * Email: lichenwei.me@foxmail.com
 */
public class WealModel implements IWealModel {

    private GankApiService mGankApiService;

    /**
     * 获取福利列表数据
     *
     * @param pageSize
     * @param currentSize
     * @param wealEntitySubscriber
     */
    @Override
    public void getWealList(int pageSize, int currentSize, Subscriber<WealEntity> wealEntitySubscriber) {
        mGankApiService = RetrofitWapper.getRetrofitWapperInstance().create(GankApiService.class);
        mGankApiService.getWealList(pageSize, currentSize).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(wealEntitySubscriber);
    }
}

这里的代码很简单,就不再做过多的文字描述了,对于Rxjava和Retrofit不熟悉的朋友可以网上查看下相关资料。

最后

关于软件开发设计模式,其实并没有最好的选择,只有更适合的选择,很多时候我们抛开业务去谈设计,架构都是飘渺的,我认为开发还是需要灵活点,不应该被某模式某架构所束缚,这样变得好像是为了目的而目的,已经脱离了设计模式最初的设计意义。
比如这个MVP,对于业务很简单的小型APP来说,有时候明明只需要几个类就可以解决的事情,非要使用MVP,会使其多了一大堆接口,导致开发成本变大,但也不是全然无用,至少它的代码层次清晰了。

      </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值