前言
记得自己接手的第二个项目采用的是 MVP 模式进行开发的,当时架构已经设计好,我看了几篇关于 MVP 的文章,对其有了基本的了解之后,便照猫画虎进行了开发,之后便再也没接触过 MVP。
最近空闲的时候读了一篇 MVP 相关的文章,受益匪浅。于是打算写一篇关于它的文章,一方面是作为自己的学习笔记方便查看,另一反面希望能给没有接触过 MVP 模式的新人提供帮助,以便可以快速入门。
什么是 MVC
在讲 MVP 之前,我们先来了解一下 MVC。
![MVC 结构图](https://i-blog.csdnimg.cn/blog_migrate/fc973d7f4842e16e25a6648c706413e8.webp?x-image-process=image/format,png)
MVC 模式是经典的三层架构一种具体的实现方式,全称为 Model(模型层) 、View(视图层)、Controller(控制器)。下面介绍一下它们各自的职责:
- Model 层:用来定义实体对象,处理业务逻辑,可以简单地理解成 Java 中的实体类。
- View 层:负责处理界面的显示,在 Android 中对应的就是 xml 文件。
- Controller 层:对应的是 Activity/Fragment ,当加载完成 xml 布局之后,我们需要找到并设置布局中的各个 View,处理用户的交互事件,更新 View 等。
下面我们通过一个简单的例子来说明这三者是如何交互的。
首先是 View 层,布局文件:
<?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="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/et_height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="身高cm"/>
<EditText
android:id="@+id/et_weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="体重kg"/>
<Button
android:id="@+id/btn_cal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
然后是 Controller 层:
public class MVCActivity extends AppCompatActivity implements View.OnClickListener {
private EditText mEtHeight;
private EditText mEtWeight;
private Button mBtnCal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Controller 访问了 View 的组件
mEtHeight = findViewById(R.id.et_height);
mEtWeight =