框架模式 MVC 在Android中的使用
- 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控制器
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119<codeclass="hljs"java="">packagecom.***.androidmvcdemo.controller;importandroid.app.Dialog;importandroid.app.ProgressDialog;importandroid.os.Bundle;importandroid.support.v7.app.ActionBarActivity;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.TextView;importandroid.widget.Toast;importcom.***.androidmvcdemo.R;importcom.***.androidmvcdemo.entity.Weather;importcom.***.androidmvcdemo.entity.WeatherInfo;importcom.***.androidmvcdemo.model.OnWeatherListener;importcom.***.androidmvcdemo.model.WeatherModel;importcom.***.androidmvcdemo.model.WeatherModelImpl;publicclassMainActivityextendsActionBarActivityimplementsOnWeatherListener, View.OnClickListener {privateWeatherModel weatherModel;privateDialog loadingDialog;privateEditText cityNOInput;privateTextView city;privateTextView cityNO;privateTextView temp;privateTextView wd;privateTextView ws;privateTextView sd;privateTextView wse;privateTextView time;privateTextView njd;@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);weatherModel =newWeatherModelImpl();initView();}/*** 初始化View*/privatevoidinitView() {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 =newProgressDialog(this);loadingDialog.setTitle(加载天气中...);}/*** 显示结果** @param weather*/publicvoiddisplayResult(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());}/*** 隐藏进度对话框*/publicvoidhideLoadingDialog() {loadingDialog.dismiss();}@OverridepublicvoidonClick(View v) {switch(v.getId()) {caseR.id.btn_go:loadingDialog.show();weatherModel.getWeather(cityNOInput.getText().toString().trim(),this);break;}}@OverridepublicvoidonSuccess(Weather weather) {hideLoadingDialog();displayResult(weather);}@OverridepublicvoidonError() {hideLoadingDialog();Toast.makeText(this, 获取天气信息失败, Toast.LENGTH_SHORT).show();}private<textends=""view=""> T findView(intid) {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代码实现
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556<codeclass="hljs"java="">packagecom.***.androidmvcdemo.model;/*** Description:请求网络数据接口* User: **** Date: 2015/6/3* Time: 15:40*/publicinterfaceWeatherModel {voidgetWeather(String cityNumber, OnWeatherListener listener);}................packagecom.***.androidmvcdemo.model;importcom.android.volley.Response;importcom.android.volley.VolleyError;importcom.***.androidmvcdemo.entity.Weather;importcom.***.androidmvcdemo.volley.VolleyRequest;/*** Description:从网络获取天气信息接口实现* User: **** Date: 2015/6/3* Time: 15:40*/publicclassWeatherModelImplimplementsWeatherModel {@OverridepublicvoidgetWeather(String cityNumber,finalOnWeatherListener listener) {/*数据层操作*/VolleyRequest.newInstance().newGsonRequest(http://www.weather.com.cn/data/sk/ + cityNumber + .html,Weather.class,newResponse.Listener<weather>() {@OverridepublicvoidonResponse(Weather weather) {if(weather !=null) {listener.onSuccess(weather);}else{listener.onError();}}},newResponse.ErrorListener() {@OverridepublicvoidonErrorResponse(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三个模块,利于代码的维护。



浙公网安备 33010602011771号