目前mvp算是一个很高效的架构,它相对于mvc模式来说减少了项目的耦合性,后期的维护和迭代都非常清晰方便。
mvp : model 层 —— 数据的存储
view层 —— activity、fragment都是属于view层
presenter层 —— 项目的逻辑交互操作基本再这一层完成
使用mvp模式后,m和v层基本不存在交互,都是通过p层来完成交互和响应作用,大大减少了activity 或者 fragment 的代码量,也使得代码结构更加清晰。后期维护迭代只需要搞懂p层基本就可以知道项目的相关功能,来进行操作维护。下面以登录实例来进行mvp模式的分析:
一、搭建基础的mvp结构
我一般写mvp结构会先写一些基础的mvp类,后面具体的类可以继承这些基本类。
基本的p层类:实现和界面view的解绑:
public interface IBasePresenter {
//解除与界面的绑定关系
void unSubscribe();
}
基本的v层类:实现加载loading 的显示和消失(具体的基本方法自己可以根据项目需求来设定):
public interface IBaseView {
//显示加载loading
void showLoadingDialog();
//取消加载loading
void hideLoadingDialog();
}
下面的是基本的presenter 逻辑操作基本实现类,实现基本的逻辑操作即view的解绑:
public class BaseCommenPresenter<T extends IBaseView> implements IBasePresenter {
public T view;
public BaseCommenPresenter(T view) {
this.view = view;
}
@Override
public void unSubscribe() {
this.view = null;
}
}
二、登录界面逻辑关系的实现
首先创建登录界面LoginActivity,设置简单登录界面的ui:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/et_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:hint="请输入手机号码"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="368dp"
android:layout_height="45dp"
android:layout_marginBottom="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:onClick="login"
android:text="登录"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
接下来就要想办法把逻辑操作分出去,不要再activity中进行大量的逻辑操作,那我们就需要创建LoginPresenter来进行登录的逻辑操作,并且需要创建LoginBaseView来进行一些界面响应即ui的更新。
我们先需要再activity中创建LoginPresenter绑定view层,还需要实现LoginBaseView进行界面ui响应
//绑定presenter层
bindPresenter(new LoginPresenter(this));
/**
* 描述:登录逻辑操作层
*/
public class LoginPresenter extends BaseCommenPresenter<LoginBaseView> implements LoginBasePresenter {
public LoginPresenter(LoginBaseView view) {
super(view);
}
@Override
public void login(String phone, String pwd) {
if (phone.equals("null")) {
view.loginFailure("登录失败");
} else {
view.loginSuccess("登录成功");
}
}
}
/**
* 描述:
*/
public interface LoginBaseView extends IBaseView {
void loginSuccess(String msg);
void loginFailure(String erro);
}
ok,基本到这里登录的mvp的简单框架已经搭建完毕。有什么问题大家可以在评论中加以反馈,希望大家相互学习哈~
github地址:mvp项目链接