MVC架構 在Android中的使用

MVC概念

MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟件設計典範,用一種業務邏輯、數據、界面顯示分離的方法組織代碼,將業務邏輯彙集到一個部件裏面,在改進和個性化定製界面及用戶交互的同時,不須要從新編寫業務邏輯。其中M層處理數據,業務邏輯等;V層處理界面的顯示結果;C層起到橋樑的做用,來控制V層和M層通訊以此來達到分離視圖顯示和業務邏輯層。說了這麼多,聽着感受很抽象,廢話很少說,咱們來看看MVC在Android開發中是怎麼應用的吧!html

這裏寫圖片描述

在Android開發中,比較流行的開發框架模式採用的是MVC框架模式,採用MVC模式的好處是便於UI界面部分的顯示和業務邏輯,數據處理分開。那麼Android項目中哪些代碼來充當M,V,C角色呢?算法

  1. M層:適合作一些業務邏輯處理,好比數據庫存取操做,網絡操做,複雜的算法,耗時的任務等都在model層處理。
  2. V層:應用層中處理數據顯示的部分,XML佈局能夠視爲V層,顯示Model層的數據結果。
  3. C層:在Android中,Activity處理用戶交互問題,所以能夠認爲Activity是控制器,Activity讀取V視圖層的數據(eg.讀取當前EditText控件的數據),控制用戶輸入(eg.EditText控件數據的輸入),並向Model發送數據請求(eg.發起網絡請求等)。

二:下面是具體代碼數據庫

 Controller控制器設計模式


public class MainActivity extends ActionBarActivity implements OnWeatherListener, View.OnClickListener {
 
    private WeatherModel weatherModel;
    private Dialog loadingDialog;
    private EditText cityNOInput;
    private TextView city;
    private TextView cityNO;
    private TextView temp;
    private TextView wd;
    private TextView ws;
    private TextView sd;
    private TextView wse;
    private TextView time;
    private TextView njd;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        weatherModel = new WeatherModelImpl();
        initView();
    }
 
    /**
     * 初始化View
     */
    private void initView() {
        cityNOInput = findView(R.id.et_city_no);
        city = findView(R.id.tv_city);
        cityNO = findView(R.id.tv_city_no);
        temp = findView(R.id.tv_temp);
        wd = findView(R.id.tv_WD);
        ws = findView(R.id.tv_WS);
        sd = findView(R.id.tv_SD);
        wse = findView(R.id.tv_WSE);
        time = findView(R.id.tv_time);
        njd = findView(R.id.tv_njd);
        findView(R.id.btn_go).setOnClickListener(this);
 
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setTitle(加載天氣中...);
 
 
    }
 
    /**
     * 顯示結果
     *
     * @param weather
     */
    public void displayResult(Weather weather) {
        WeatherInfo weatherInfo = weather.getWeatherinfo();
        city.setText(weatherInfo.getCity());
        cityNO.setText(weatherInfo.getCityid());
        temp.setText(weatherInfo.getTemp());
        wd.setText(weatherInfo.getWD());
        ws.setText(weatherInfo.getWS());
        sd.setText(weatherInfo.getSD());
        wse.setText(weatherInfo.getWSE());
        time.setText(weatherInfo.getTime());
        njd.setText(weatherInfo.getNjd());
    }
 
    /**
     * 隱藏進度對話框
     */
    public void hideLoadingDialog() {
        loadingDialog.dismiss();
    }
 
 
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_go:
                loadingDialog.show();
                weatherModel.getWeather(cityNOInput.getText().toString().trim(), this);
                break;
        }
    }
 
    @Override
    public void onSuccess(Weather weather) {
        hideLoadingDialog();
        displayResult(weather);
    }
 
    @Override
    public void onError() {
        hideLoadingDialog();
        Toast.makeText(this, 獲取天氣信息失敗, Toast.LENGTH_SHORT).show();
    }
 
   private <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }網絡

 
}框架

從上面代碼能夠看到,Activity持有了WeatherModel模型的對象,當用戶有點擊Button交互的時候,Activity做爲Controller控制層讀取View視圖層EditTextView的數據,而後向Model模型發起數據請求,也就是調用WeatherModel對象的方法 getWeathre()方法。當Model模型處理數據結束後,經過接口OnWeatherListener通知View視圖層數據處理完畢,View視圖層該更新界面UI了。而後View視圖層調用displayResult()方法更新UI。至此,整個MVC框架流程就在Activity中體現出來了。ide

Model模型


 
/**
 * Description:請求網絡數據接口
 
 */
 
public interface WeatherModel {
    void getWeather(String cityNumber, OnWeatherListener listener);
}
 

 
/**
 * Description:從網絡獲取天氣信息接口實現
 
 */
 
public class WeatherModelImpl implements WeatherModel {
 
    @Override
    public void getWeather(String cityNumber, final OnWeatherListener listener) {
 
        /*數據層操做*/
        VolleyRequest.newInstance().newGsonRequest(http://www.weather.com.cn/data/sk/ + cityNumber + .html,
                Weather.class, new Response.Listener<weather>() {
                    @Override
                    public void onResponse(Weather weather) {
                        if (weather != null) {
                            listener.onSuccess(weather);
                        } else {
                            listener.onError();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        listener.onError();
                    }
                });
    }
}模塊化

以上代碼看出,這裏設計了一個WeatherModel模型接口,而後實現了接口WeatherModelImpl類。controller控制器activity調用WeatherModelImpl類中的方法發起網絡請求,而後經過實現OnWeatherListener接口來得到網絡請求的結果通知View視圖層更新UI 。至此,Activity就將View視圖顯示和Model模型數據處理隔離開了。activity擔當contronller完成了model和view之間的協調做用。佈局

至於這裏爲何不直接設計成類裏面的一個getWeather()方法直接請求網絡數據?你考慮下這種狀況:如今代碼中的網絡請求是使用Volley框架來實現的,若是哪天老闆非要你使用Afinal框架實現網絡請求,你怎麼解決問題?難道是修改 getWeather()方法的實現? no no no,這樣修改不只破壞了之前的代碼,並且還不利於維護, 考慮到之後代碼的擴展和維護性,咱們選擇設計接口的方式來解決着一個問題,咱們實現另一個WeatherModelWithAfinalImpl類,繼承自WeatherModel,重寫裏面的方法,這樣不只保留了之前的WeatherModelImpl類請求網絡方式,還增長了WeatherModelWithAfinalImpl類的請求方式。Activity調用代碼無須要任何修改。this

MVC使用總結

  1. 利用MVC設計模式,使得這個天氣預報小項目有了很好的可擴展和維護性,當須要改變UI顯示的時候,無需修改Contronller(控制器)Activity的代碼和Model(模型)WeatherModel模型中的業務邏輯代碼,很好的將業務邏輯和界面顯示分離。

  2. 在Android項目中,業務邏輯,數據處理等擔任了Model(模型)角色,XML界面顯示等擔任了View(視圖)角色,Activity擔任了Contronller(控制器)角色。contronller(控制器)是一箇中間橋樑的做用,經過接口通訊來協同 View(視圖)和Model(模型)工做,起到了二者之間的通訊做用。

  3. 何時適合使用MVC設計模式?固然一個小的項目且無需頻繁修改需求就不用MVC框架來設計了,那樣反而以爲代碼過分設計,代碼臃腫。通常在大的項目中,且業務邏輯處理複雜,頁面顯示比較多,須要模塊化設計的項目使用MVC就有足夠的優點了。

    4.在MVC模式中咱們發現,其實控制器Activity主要是起到解耦做用,將View視圖和Model模型分離,雖然Activity起到交互做用,可是找Activity中有不少關於視圖UI的顯示代碼,所以View視圖和Activity控制器並非徹底分離的,也就是說一部分View視圖和Contronller控制器Activity是綁定在一個類中的。

  4. MVC的優勢:

    (1)耦合性低。所謂耦合性就是模塊代碼之間的關聯程度。利用MVC框架使得View(視圖)層和Model(模型)層能夠很好的分離,這樣就達到了解耦的目的,因此耦合性低,減小模塊代碼之間的相互影響。

    (2)可擴展性好。因爲耦合性低,添加需求,擴展代碼就能夠減小修改以前的代碼,下降bug的出現率。

    (3)模塊職責劃分明確。主要劃分層M,V,C三個模塊,利於代碼的維護。

相關文章
相關標籤/搜索