1. MVC介紹
MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫毙驯,是一種框架模式倒堕。
Model:模型層,負責(zé)處理數(shù)據(jù)的加載或存儲爆价。
View:視圖層垦巴,負責(zé)界面數(shù)據(jù)的展示,與用戶進行交互铭段。
Controller:控制器層骤宣,負責(zé)邏輯業(yè)務(wù)的處理。
1.1 作用
將業(yè)務(wù)邏輯序愚、數(shù)據(jù)憔披、界面分離的一種代碼組織方式,修改界面時無需去修改業(yè)務(wù)邏輯爸吮。
1.2 流程
1.View接受用戶的請求芬膝,然后將請求傳遞給Controller。
2.Controller進行業(yè)務(wù)邏輯處理后形娇,通知Model去更新锰霜。
3.Model數(shù)據(jù)更新后,通知View去更新界面顯示桐早。
1.3 關(guān)系
一個模型可以有多個視圖癣缅,一個視圖可以有多個控制器,一個控制器也可以有多個模型勘畔。
2. MVC例子實現(xiàn)
Android中一般布局的XML文件就是View層所灸,Activity
則充當(dāng)了Controller的角色。
下面舉個簡單的例子來實現(xiàn)炫七,點擊按鈕對數(shù)字+1然后重新顯示出來。
2.1 Model層
創(chuàng)建一個數(shù)據(jù)模型钾唬,能夠保存一個數(shù)字万哪,并有一個更新的方法,數(shù)據(jù)更新完后會通知UI去更改顯示的內(nèi)容抡秆。
public class NumModel {
private int num = 0;
public void add(ControllerActivity activity) {
num = ++num;//更新數(shù)據(jù)
activity.updateUI(num + "");//更新UI
}
}
2.2 View層
View層在Android中對應(yīng)的就是布局的XML文件奕巍。
activity_controller.xml :
<?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">
<TextView
android:id="@+id/tv_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"/>
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點擊+1"/>
</LinearLayout>
2.3 Controller層
Android中一般由Activity
來充當(dāng)Controller。Controller一方面接收來自View的事件儒士,一方面通知Model處理數(shù)據(jù)的止。
public class ControllerActivity extends Activity {
private TextView mTextView;
private Button mButton;
private NumModel mNumModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controller);
mTextView = findViewById(R.id.tv_show);
mButton = findViewById(R.id.btn_add);
mNumModel = new NumModel();
mButton.setOnClickListener(new View.OnClickListener() {//接收來自View的事件
@Override
public void onClick(View v) {
mNumModel.add(ControllerActivity.this);//通知Model處理數(shù)據(jù)
}
});
}
public void updateUI(String text) {//更新UI
mTextView.setText(text);
}
}
3. Android中的源碼應(yīng)用
Android中最典型的MVC莫過于ListView
了,要顯示的數(shù)據(jù)為Model着撩,而要顯示的ListView
就是View了诅福,Adapter
則充當(dāng)著Controller的角色匾委。當(dāng)Model發(fā)生改變的時候可以通過調(diào)用Adapter
的notifyDataSetChanged
方法來通知組件數(shù)據(jù)發(fā)生變化,這時Adapter會調(diào)用getView
方法重新顯示內(nèi)容氓润。具體代碼這里就不分析了赂乐。
4. MVC的優(yōu)點
- 視圖層(View)與模型層(Model)解偶,通過Controller來進行聯(lián)系咖气。
- 模塊職責(zé)劃分明確挨措。主要劃分層M,V,C三個模塊,利于代碼的維護崩溪。
5. MVC的缺點
- Android中使用了
Activity
來充當(dāng)Controller浅役,但實際上一些UI也是由Activity
來控制的,比如進度條等伶唯。因此部分視圖就會跟Controller捆綁在同一個類了觉既。同時,由于Activity
的職責(zé)過大抵怎,Activity
類的代碼也會迅速膨脹奋救。 - MVC還有一個重要的缺陷就是View跟Model是有交互的,沒有做到完全的分離反惕,這就會產(chǎn)生耦合尝艘。
6.其他
雖然MVC很簡單,但是如果項目比較小且無需頻繁修改的話姿染,就可以不用MVC了背亥,避免過度設(shè)計,造成維護困難悬赏。
鑒于MVC的缺點狡汉,誕生了MVP來解決這些問題,下一篇文章繼續(xù)來說明~
相關(guān)文章閱讀
Android框架模式——MVC
Android框架模式——MVP
Android框架模式——MVVM