MVC模式
- Model:代表一個數(shù)據(jù)對象也切±资眩可以帶一些邏輯倒槐,在數(shù)據(jù)變化時更新控制器葵萎。
- View:數(shù)據(jù)的可視化
- Controller:控制數(shù)據(jù)流向模型對象唱凯,并在數(shù)據(jù)變化時更新視圖卷雕。
View
在Android中視圖層被封裝成了XML文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp">
<View
......../>
</LinearLayout>
Controller
在Android中控制層也就是Activity
public class MainActivity extends ActionBarActivity implements OnWeatherListener, View.OnClickListener {
private WeatherModel weatherModel;
private Dialog loadingDialog;
@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);
loadingDialog = new ProgressDialog(this);
loadingDialog.setTitle("加載天氣中...");
}
/**
* 顯示結(jié)果
*
* @param weather
*/
public void displayResult(Weather weather) {
WeatherInfo weatherInfo = weather.getWeatherinfo();
city.setText(weatherInfo.getCity());
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();
}
}
Model層
指數(shù)據(jù)來源,Android中目前一般指網(wǎng)絡(luò)請求返回的數(shù)據(jù),大多時候這是已經(jīng)被封裝好的一層速缨。
public interface OnWeatherListener {
void onSuccess(Weather weather);
void onError();
}
public interface WeatherModel {
void getWeather(String cityNumber, OnWeatherListener listener);
}
public class WeatherModelImpl implements WeatherModel {
@Override
public void getWeather(String cityNumber, final OnWeatherListener listener) {
/*數(shù)據(jù)層操作*/
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();
}
});
}
}
個人評價
在MVC的設(shè)計架構(gòu)中捡偏,Activity做為Controller本身的作用是鏈接Model和View的紐帶峡迷,其本身不會負責(zé)太多的職責(zé),但是實際使用過程中彤避,Activity本身還要處理響應(yīng)用戶的操作夯辖,隨著頁面交互的復(fù)雜性增加,Activity中的代碼也會變得十分臃腫蒿褂。