算来学习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层:界面UI的显示,XML布局可以视为V层,当然还包括对界面UI显示逻辑处理数据的结果的操作代码。
C层:在Android中,Activity可以认为是控制器,Activity发起业务逻辑请求处理,等待业务处理结果,然后将结果通知View更新界面。
接下来我们通过一个获取天气预报数据的小项目来解读 MVC for Android。先上一个界面图:
我们开始写代码,先从Activity实现看起:
package com.xjp.androidmvcdemo.controller; import android.app.Dialog; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; 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; /** * Description: * User: xjp * Date: 2015/6/3 * Time: 16:26 */ public class WeatherActivity extends ActionBarActivity { 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(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } /** * 初始化View */ private void initView() { cityNOInput = (EditText) findViewById(R.id.et_city_no); city = (TextView) findViewById(R.id.tv_city); cityNO = (TextView) findViewById(R.id.tv_city_no); temp = (TextView) findViewById(R.id.tv_temp); wd = (TextView) findViewById(R.id.tv_WD); ws = (TextView) findViewById(R.id.tv_WS); sd = (TextView) findViewById(R.id.tv_SD); wse = (TextView) findViewById(R.id.tv_WSE); time = (TextView) findViewById(R.id.tv_time); njd = (TextView) findViewById(R.id.tv_njd); loadingDialog = new ProgressDialog(this); loadingDialog.setTitle("加载天气中..."); findViewById(R.id.btn_go).setOnClickListener(this); } /** * 显示结果 * * @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()); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_go: loadingDialog.show(); //执行网络请求 break; } }
从上面代码可以看到,Activity负责了View视图UI的响应事件和请求结果视图显示。以上代码看起来貌似没什么问题,但是从代码的可扩展性,可维护性考虑,这样写代码就有弊端:当客户的View视图显示需求发生改变之后,我们不得不去修改Activity中的代码,来修改View视图显示。当界面显示修改比较大的时候,Activity里的代码修改也很大,这么一来导致Activity代码臃肿,不利于维护,也很有可能在修改Activity的时候导致Activity中其他部分代码出错。因此,我们不提倡在Activity中来写View界面显示。根据MVC设计模式开发,将View视图分离出来,减轻Activity的负担,让Activity来担任Controller角色。看看代码实现如下:
看看工程目录结构如图:

View视图
package com.xjp.androidmvcdemo.view; import android.app.Dialog; import android.app.ProgressDialog; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.xjp.androidmvcdemo.R; import com.xjp.androidmvcdemo.entity.Weather; import com.xjp.androidmvcdemo.entity.WeatherInfo; /** * Description:将天气信息显示到View * User: xjp * Date: 2015/6/3 * Time: 14:55 */ public class DisplayWeatherInfoView { private ActionBarActivity activity; RequestWeatherView iRequest; 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; public DisplayWeatherInfoView(ActionBarActivity activity, RequestWeatherView iRequest) { this.activity = activity; this.iRequest = iRequest; initView(); } /** * 初始化View */ private void initView() { cityNOInput = (EditText) activity.findViewById(R.id.et_city_no); city = (TextView) activity.findViewById(R.id.tv_city); cityNO = (TextView) activity.findViewById(R.id.tv_city_no); temp = (TextView) activity.findViewById(R.id.tv_temp); wd = (TextView) activity.findViewById(R.id.tv_WD); ws = (TextView) activity.findViewById(R.id.tv_WS); sd = (TextView) activity.findViewById(R.id.tv_SD); wse = (TextView) activity.findViewById(R.id.tv_WSE); time = (TextView) activity.findViewById(R.id.tv_time); njd = (TextView) activity.findViewById(R.id.tv_njd); loadingDialog = new ProgressDialog(activity); loadingDialog.setTitle("加载天气中..."); activity.findViewById(R.id.btn_go).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadingDialog.show(); iRequest.sendRequest(cityNOInput.getText().toString().trim()); } }); } /** * 显示结果 * * @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(); } }
我们将View界面控制提成一个DisplayWeatherInfoView类,这个类实现了View的查找初始化和View界面结果的显示,以及View响应事件的接口。所有的界面操作都在这个类了。
Controller控制器
接下来看看Activity是怎么调用DisplayWeatherInfoView类的。
package com.xjp.androidmvcdemo.controller; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.Toast; import com.xjp.androidmvcdemo.R; import com.xjp.androidmvcdemo.model.OnWeatherListener; import com.xjp.androidmvcdemo.entity.Weather; import com.xjp.androidmvcdemo.model.WeatherModel; import com.xjp.androidmvcdemo.model.WeatherModelImpl; import com.xjp.androidmvcdemo.view.DisplayWeatherInfoView; import com.xjp.androidmvcdemo.view.RequestWeatherView; public class MainActivity extends ActionBarActivity implements RequestWeatherView, OnWeatherListener { private DisplayWeatherInfoView displayView; private static WeatherModel weatherModel = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); displayView = new DisplayWeatherInfoView(this, this); if (null == weatherModel) { weatherModel = new WeatherModelImpl(); } } @Override public void sendRequest(String number) { weatherModel.getWeather(number, this); } @Override public void onSuccess(Weather weather) { displayView.hideLoadingDialog(); displayView.displayResult(weather); } @Override public void onError() { displayView.hideLoadingDialog(); Toast.makeText(this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); } }
以上代码可以看出,Activity持有了DisplayWeatherInfoView对象引用,并且实现了RequestWeatherView控件响应事件接口。当View视图有类似用户点击响应事件的时候,会以接口通信的方式通知Activity,View发生了用户响应事件,让Activity去做相应的处理,此时Activity充当Controller角色,来将用户的响应请求发送到 model层,让model层来处理网络请求。因此Activity 同时持有model的对象引用WeatherModelImpl。
Model模型
来看看WeatherModelImpl代码实现
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(); } }); } }
以上代码看出,这里设计了一个WeatherModel模型接口,然后实现了接口WeatherModelImpl类。至于这里为什么不直接设计成类里面的一个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就有足够的优势了。
MVC的优点:
(1)耦合性低。所谓耦合性就是模块代码之间的关联程度。利用MVC框架使得View(视图)层和Model(模型)层可以很好的分离,这样就达到了解耦的目的,所以耦合性低,减少模块代码之间的相互影响。
(2)可扩展性好。由于耦合性低,添加需求,扩展代码就可以减少修改之前的代码,降低bug的出现率。
(3)模块职责划分明确。主要划分层M,V,C三个模块,利于代码的维护。
作者:goodboy369