算來學習Android開發已有2年的歷史了,在這2年的學習當中,基本掌握了Android的基礎知識。越到后面的學習越感覺困難,一來是自認為android沒啥可學的了(自認為的,其實還有很多知識科學),二來網絡上的很多框架已經幫我們做了太多的事情了,我們只需要畫畫UI就可以了,感覺Android開發沒有太多的技術含金量。最近閑來無事,開始總結之前學過的知識點,想着是否應該學點其他的東西呢?總不能局限於Android基礎知識吧。慢慢的探索發現在大的項目工程中,一個好的框架,好的設計模式,能減少很大的工作量。因此接下來兩篇博客來學習一下Android中常用的兩種框架設計模式 MVC和MVP。
MVC概念
MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟件設計典范,用一種業務邏輯、數據、界面顯示分離的方法組織代碼,將業務邏輯聚集到一個部件里面,在改進和個性化定制界面及用戶交互的同時,不需要重新編寫業務邏輯。其中M層處理數據,業務邏輯等;V層處理界面的顯示結果;C層起到橋梁的作用,來控制V層和M層通信以此來達到分離視圖顯示和業務邏輯層。說了這么多,聽着感覺很抽象,廢話不多說,我們來看看MVC在Android開發中是怎么應用的吧!
MVC for Android
在Android開發中,比較流行的開發框架模式采用的是MVC框架模式,采用MVC模式的好處是便於UI界面部分的顯示和業務邏輯,數據處理分開。那么Android項目中哪些代碼來充當M,V,C角色呢?
M層:適合做一些業務邏輯處理,比如數據庫存取操作,網絡操作,復雜的算法,耗時的任務等都在model層處理。 V層:應用層中處理數據顯示的部分,XML布局可以視為V層,顯示Model層的數據結果。 C層:在Android中,Activity處理用戶交互問題,因此可以認為Activity是控制器,Activity讀取V視圖層的數據(eg.讀取當前EditText控件的數據),控制用戶輸入(eg.EditText控件數據的輸入),並向Model發送數據請求(eg.發起網絡請求等)。
接下來我們通過一個獲取天氣預報數據的小項目來解讀 MVC for Android。先上一個界面圖:
Controller控制器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
<code
class
=
"hljs"
java=
""
>
package
com.xjp.androidmvcdemo.controller;
import
android.app.Dialog;
import
android.app.ProgressDialog;
import
android.os.Bundle;
import
android.support.v7.app.ActionBarActivity;
import
android.view.View;
import
android.widget.EditText;
import
android.widget.TextView;
import
android.widget.Toast;
import
com.xjp.androidmvcdemo.R;
import
com.xjp.androidmvcdemo.entity.Weather;
import
com.xjp.androidmvcdemo.entity.WeatherInfo;
import
com.xjp.androidmvcdemo.model.OnWeatherListener;
import
com.xjp.androidmvcdemo.model.WeatherModel;
import
com.xjp.androidmvcdemo.model.WeatherModelImpl;
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);
}
}
</t></code>
|
從上面代碼可以看到,Activity持有了WeatherModel模型的對象,當用戶有點擊Button交互的時候,Activity作為Controller控制層讀取View視圖層EditTextView的數據,然后向Model模型發起數據請求,也就是調用WeatherModel對象的方法 getWeathre()方法。當Model模型處理數據結束后,通過接口OnWeatherListener通知View視圖層數據處理完畢,View視圖層該更新界面UI了。然后View視圖層調用displayResult()方法更新UI。至此,整個MVC框架流程就在Activity中體現出來了。
Model模型
來看看WeatherModelImpl代碼實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<code
class
=
"hljs"
java=
""
>
package
com.xjp.androidmvcdemo.model;
/**
* Description:請求網絡數據接口
* User: xjp
* Date: 2015/6/3
* Time: 15:40
*/
public
interface
WeatherModel {
void
getWeather(String cityNumber, OnWeatherListener listener);
}
................
package
com.xjp.androidmvcdemo.model;
import
com.android.volley.Response;
import
com.android.volley.VolleyError;
import
com.xjp.androidmvcdemo.entity.Weather;
import
com.xjp.androidmvcdemo.volley.VolleyRequest;
/**
* Description:從網絡獲取天氣信息接口實現
* User: xjp
* Date: 2015/6/3
* Time: 15:40
*/
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();
}
});
}
}
</weather></code>
|
以上代碼看出,這里設計了一個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調用代碼無需要任何修改。
MVC使用總結
利用MVC設計模式,使得這個天氣預報小項目有了很好的可擴展和維護性,當需要改變UI顯示的時候,無需修改Contronller(控制器)Activity的代碼和Model(模型)WeatherModel模型中的業務邏輯代碼,很好的將業務邏輯和界面顯示分離。
在Android項目中,業務邏輯,數據處理等擔任了Model(模型)角色,XML界面顯示等擔任了View(視圖)角色,Activity擔任了Contronller(控制器)角色。contronller(控制器)是一個中間橋梁的作用,通過接口通信來協同 View(視圖)和Model(模型)工作,起到了兩者之間的通信作用。
什么時候適合使用MVC設計模式?當然一個小的項目且無需頻繁修改需求就不用MVC框架來設計了,那樣反而覺得代碼過度設計,代碼臃腫。一般在大的項目中,且業務邏輯處理復雜,頁面顯示比較多,需要模塊化設計的項目使用MVC就有足夠的優勢了。
4.在MVC模式中我們發現,其實控制器Activity主要是起到解耦作用,將View視圖和Model模型分離,雖然Activity起到交互作用,但是找Activity中有很多關於視圖UI的顯示代碼,因此View視圖和Activity控制器並不是完全分離的,也就是說一部分View視圖和Contronller控制器Activity是綁定在一個類中的。
MVC的優點:
(1)耦合性低。所謂耦合性就是模塊代碼之間的關聯程度。利用MVC框架使得View(視圖)層和Model(模型)層可以很好的分離,這樣就達到了解耦的目的,所以耦合性低,減少模塊代碼之間的相互影響。
(2)可擴展性好。由於耦合性低,添加需求,擴展代碼就可以減少修改之前的代碼,降低bug的出現率。
(3)模塊職責划分明確。主要划分層M,V,C三個模塊,利於代碼的維護。