Android 你应该学会的设计模式MVP

MVP大家最先想到的应该是LOL和CF里面的MVP荣誉吧,玩过的应该都知道指的是Most-Valuable-Player(全场表现最佳DE游戏玩家)

以前也经常玩,平常凌晨一两点,周末凌晨三四点,想想那段时间还是挺疯的,浪费了那么多时间,现在得赶紧抓紧时间好好学习,多写简书,好好工作,定个小目标,挣他一个亿!

好了废话就不多说,进入正题,我们这里说的MVP则是一种设计模式,说起MVP那就要先说说MVC设计模式了,MVP就是由MVC演变而来的。

MVC由Model、View、Control组成。
Model数据模型,提供数据
View视图模型,提供视图展示
Control控制器,负责控制Model和View通信

MVC在Android中的应用,如下图,Activity为Control,XML为View,请求网络数据模块为Model。View箭头指向Control意为传递数据,那就是Control获取View的数据传递给Model来请求网络,请求到的数据直接传递给View来显示,这是一条主线。还有一条就是底部这两个箭头,也就是说Model可以不通过Control,直接获取View的数据,然后再返回结果数据给View。

MVC.png

MVP由Model、View、Presenter组成。
Model数据模型,提供数据
View视图模型,提供视图展示
Presenter主持者,负责逻辑处理

MVP与MVC最明显的区别就在于Presenter和Control了。如下图,Presenter传递数据给Model,Model得到数据来请求网络,再返回数据给Presenter,Presenter再把得到的Model数据传递给View显示。MVP整体的一个流程就是这样。相比MVC来说,Model和View互相不干涉,达到完全解耦

MVP.png

估计上面文字性的解释都听得有点晕,那我们就拿个例子来实战一下吧

下面和大家一起完成一个简单查询快递信息的例子,里面用到了当下最流行的架构RxJava+Retrofit+MVP+OkHttp,非常值得大家一学

配置环境

在builde.gradle里面添加

compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.1.6'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

在AndroidManifest.xml添加所需权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

初始化配置Retrofit

public class MainApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //初始化retrofitUtils
        RetrofitUtils.getInstance().initOkHttp(this);
    }
}

在MainApp中初始化Retrofit,设置超时和baseUrl,添加了日志拦截以及RxJava和数据解析,并暴露一个getRetrofit()方法供需要的地方调用

public class RetrofitUtils {
    private Retrofit retrofit;
    private String baseUrl = "http://www.kuaidi100.com/";
    private static class SingleLoader{
        private static final RetrofitUtils INSTANCE = new RetrofitUtils();
    }
    public static RetrofitUtils getInstance(){
        return SingleLoader.INSTANCE;
    }
    public void initOkHttp(@NonNull Context context){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000L,TimeUnit.MILLISECONDS)       //设置连接超时
                .readTimeout(10000L,TimeUnit.MILLISECONDS)          //设置读取超时
                .writeTimeout(10000L, TimeUnit.MILLISECONDS)         //设置写入超时
                .cache(new Cache(context.getCacheDir(),10 * 1024 * 1024))   //设置缓存目录和10M缓存
                .addInterceptor(interceptor)    //添加日志拦截器(该方法也可以设置公共参数,头信息)
                .build();
        retrofit = new Retrofit.Builder()
                .client(client)     //设置OkHttp
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create()) //  添加数据解析ConverterFactory
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())   //添加RxJava
                .build();
    }
    public Retrofit getRetrofit(){
        return retrofit;
    }
}

Model

public interface PostSearchModel {
    /**
     * 请求快递信息
     * @param type 快递类型
     * @param postid 快递单号
     * @param callback 结果回调
     */
    void requestPostSearch(String type,String postid,PostSearchCallback callback);
    interface PostSearchCallback{
        void requestPostSearchSuccess(PostQueryInfo postQueryInfo);
        void requestPostSearchFail(String failStr);
    }
}

创建这个PostSearchModel接口,方便后期可以不修改之前代码灵活切换多种实现方式

public interface PostServiceBiz {
    @POST("query")
    Observable<PostQueryInfo> searchRx(@Query("type") String type, @Query("postid") String postid);
}
public class PostQueryInfo {
    private String message;
    private String nu;
    private String ischeck;
    private String com;
    private String status;
    private String condition;
    private String state;
    private List<DataBean> data;
    public static class DataBean {
        private String time;
        private String context;
        private String ftime;
    }
}

PostQueryInfo没有添加get和set方法,大家自行快捷键了
PostSearchModelImpl实现上面PostSearchModel接口,利用上一篇文章里学的Retrofit结合RxJava来请求网络
这里传了PostSearchCallback回调函数,成功或者失败都通过回调函数返回,完全不需要考虑其它

public class PostSearchModelImpl implements PostSearchModel {
    @Override
    public void requestPostSearch(String type, String postid, final PostSearchCallback callback) {
        RetrofitUtils.getInstance()
                .getRetrofit()
                .create(PostServiceBiz.class)
                .searchRx(type,postid)
                //访问网络切换异步线程
                .subscribeOn(Schedulers.io())
                //响应结果处理切换成主线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PostQueryInfo>() {
                    @Override
                    public void onCompleted() {
                        //请求结束回调
                    }
                    @Override
                    public void onError(Throwable e) {
                        //错误回调
                        callback.requestPostSearchFail(e.getMessage());
                    }
                    @Override
                    public void onNext(PostQueryInfo postQueryInfo) {
                        //成功结果返回
                        callback.requestPostSearchSuccess(postQueryInfo);
                    }
                });
    }
}

View

activity_main.xml主界面布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".ui.MainActivity"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="快递公司名:"/>
        <EditText
            android:id="@+id/post_name_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="yuantong"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="快 递  单 号:"
            />
        <EditText
            android:id="@+id/post_id_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="500379523313"/>
    </LinearLayout>
    <Button
        android:id="@+id/post_search_bn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"/>
    <ListView
        android:id="@+id/post_list_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:listSelector="@null"
        android:background="@null"/>
</LinearLayout>

view_item_logistics.xml
listview适配器的item布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="15dp">
    <TextView
        android:id="@+id/tv_conent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#8f8f8f"
        android:textSize="14sp"
        android:text="【深圳市】广东分公司已出发" />
    <TextView
        android:layout_marginTop="13dp"
        android:id="@+id/tv_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#8f8f8f"
        android:textSize="12sp"
        android:layout_marginBottom="13dp"
        android:paddingLeft="6dp"
        android:text="2016-05-03 18:23" />
</LinearLayout>

ListView适配器

public class LogisticsAdapter extends BaseAdapter {
    private List<PostQueryInfo.DataBean> datas;
    private LayoutInflater inflater;
    public LogisticsAdapter(Context context, List<PostQueryInfo.DataBean> datas) {
        this.datas = datas;
        inflater = LayoutInflater.from(context);
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        PostQueryInfo.DataBean data = datas.get(i);
        view = inflater.inflate(R.layout.view_item_logistics, null);
        TextView tv_content= (TextView) view.findViewById(R.id.tv_conent);
        TextView tv_date= (TextView) view.findViewById(R.id.tv_date);
        tv_content.setText(data.getContext().replace("[","【").replace("]","】"));
        tv_date.setText(data.getTime());
        return view;
    }
    @Override
    public int getCount() {
        return datas != null ? datas.size() : 0;
    }
    @Override
    public Object getItem(int i) {
        return datas.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
}

BaseView提供通用显示和隐藏加载框,如果有通用的方法都可以在写在这里面

public interface BaseView {
    void showProgressDialog();    
    void hideProgressDialog();
}

MainView接口继承提供MainActivity所有需要更新界面UI的方法

public interface MainView extends BaseView{
    void updateListUI(PostQueryInfo postQueryInfo);
    void errorToast(String message);
}

BaseActivity实现BaseVew所有接口方法

public class BaseActivity extends Activity implements BaseView{
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("查询中...");
    }
    @Override
    public void showProgressDialog(){
        if(progressDialog!=null){
            progressDialog.show();
        }
    }
    @Override
    public void hideProgressDialog(){
        if(progressDialog!=null&&progressDialog.isShowing()){
            progressDialog.dismiss(); 
       }
    }
}

MainActivity继承BaseActivity实现MainView所有方法供PostPresenter调用,点击查询按钮通过实例化的PostPresenter,调用相关方法,后面的事情就全部交给PostPresenter去处理了,在activity销毁的时候调用postPresenter.detach()防止内存泄漏

public class MainActivity extends BaseActivity implements View.OnClickListener, MainView {
    private EditText post_name_et;
    private EditText post_id_et;
    private ListView post_list_lv;
    private Button post_search_bn;
    private PostPresenter postPresenter;
    private List<PostQueryInfo.DataBean> dataArray = new ArrayList<>();
    private LogisticsAdapter logisticsAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();
    }
    private void initView() {
        post_name_et = (EditText) findViewById(R.id.post_name_et);
        post_id_et = (EditText) findViewById(R.id.post_id_et);
        post_list_lv = (ListView) findViewById(R.id.post_list_lv);
        post_search_bn = (Button) findViewById(R.id.post_search_bn);
    }
    private void initData() {
        logisticsAdapter = new LogisticsAdapter(getApplicationContext(),dataArray);
        postPresenter = new PostPresenter(this);
        post_list_lv.setAdapter(logisticsAdapter);
    }
    private void initEvent() {
        post_search_bn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.post_search_bn:
           postPresenter.requestHomeData(post_name_et.getText().toString(),post_id_et.getText().toString());
                break;
        }
    }
    @Override
    public void updateListUI(PostQueryInfo postQueryInfo) {
        dataArray.clear();
        dataArray.addAll(postQueryInfo.getData());
        logisticsAdapter.notifyDataSetChanged();
    }
    @Override
    public void errorToast(String message) {
        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
    }
    @Override
    protected void onDestroy(){
        //防止activity销毁,postPresenter对象还存在造成的内存泄漏
        if(postPresenter!=null) postPresenter.detach();
        super.onDestroy();
    }
}

Presenter

BasePresenter基类,提供了一个通用view对象,以及初始化和销毁view对象的方法

public abstract class BasePresenter<T>{
    public T mView;
    public void attach(T view){
        this.mView = view;
    }
    public void detach(){
        mView = null;
    }
}

PostPresenter在构造函数中通过基类attach的方法初始化MainActivity提供的view对象,实例化PostSearchModelImpl对象,通过它提供的方法来请求网络数据,在成功和失败回调的函数里,可以做一些逻辑处理,通过view对象更新相应的UI

public class PostPresenter extends BasePresenter<MainView>{
    private PostSearchModel postSearchModel;
    public PostPresenter(MainView mainView){
        attach(mainView);
        postSearchModel = new PostSearchModelImpl();
    }
    public void requestHomeData(String type,String postid){
        if(postSearchModel == null||mView == null)
            return;
        mView.showProgressDialog();
        postSearchModel.requestPostSearch(type, postid, new PostSearchModel.PostSearchCallback() {
            @Override
            public void requestPostSearchSuccess(PostQueryInfo postQueryInfo) {
                mView.hideProgressDialog();
                if(postQueryInfo!=null&&"ok".equals(postQueryInfo.getMessage())) {
                    mView.updateListUI(postQueryInfo);
                }
            }
            @Override
            public void requestPostSearchFail(String failStr) {
                mView.hideProgressDialog();
                mView.errorToast(failStr);
            }
        });
    }
}

到这里全部代码基本都已编写完,代码的结构如下图:

MVP结构图.png

下面就运行程序看看效果吧,快递公司名和快递单号默认填写上去了,大家只需要点击查询,结果和下面图片一样就说明成功了

快递查询.png

为什么没有直接提供一个可以运行的DEMO出来,原因很简单就是希望大家能够跟着一步一步学习,然后动手慢慢边敲代码边理解,最后敲完运行成功,应该就会更加理解MVP了。

Tips

上面MVC、MVP流程图制作的网站分享个大家:
https://www.processon.com/
这个网站还可以做四维导图、UI原型图和UML图等等很多,有需要的可以去看看

成功源于不断的学习和积累

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容