Design Mode MVC for Android

Source: Internet
Author: User

Design Mode MVC for Android

I have been learning about Android development for two years. During these two years, I have mastered the basic knowledge of Android. The more difficult it is to learn later, the more difficult it is to think that android has nothing to learn (in fact, there is still a lot of knowledge and science ), secondly, many frameworks on the network have already helped us with too many things. We only need to draw the UI and feel that there is not much gold in Android development. I have nothing to worry about recently. I started to summarize the previous knowledge points and thought about whether I should learn other things? It cannot be limited to basic Android knowledge. Slowly exploring and discovering that a good framework and a good design model can reduce the workload of large projects. So the next two blogs will learn about the two common framework design patterns in Android: MVC and MVP.

MVC Concept

The full name of MVC is Model View Controller, short for model-view-controller. It is a Model of software design, organize Code by means of separation of business logic, data, and interface display, and integrate the business logic into a component to improve and personalize the custom interface and user interaction, you do not need to rewrite the business logic. Among them, the M layer processes data and business logic; the V layer processes the Display Results of the interface; the C layer serves as a bridge, to control the communication between the V layer and the M layer to achieve the separation of View display and business logic layer. After talking so much about it, I feel very abstract. I don't talk much about it. Let's take a look at how MVC is applied in Android development!

MVC for Android

In Android development, the most popular development framework pattern adopts the MVC design pattern. The advantage of using the MVC pattern is to facilitate the display of part of the UI interface and separate the business logic and data processing. What code does the Android project use to act as M, V, and C?

M layer: Suitable for some business logic processing, such as database operations, network operations, complex algorithms, and time-consuming tasks. V layer: Display of the UI. XML layout can be regarded as V layer. Of course, operation code for displaying the result of logical data processing on the UI is also included. Layer C: In Android, the Activity can be considered as a controller. The Activity initiates a business logic request for processing, waits for the business processing results, and then notifies the View to update the interface.

Next we will use a small project to get weather forecast data to interpret MVC for Android. First, the interface is shown as follows:

We started to write the code, starting with the implementation of the Activity: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> 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 ();}/*** initialize 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 (loading weather ...); findViewById (R. id. btn_go ). setOnClickListener (this);}/*** display result ** @ 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 (); // execute the network request break ;}}

The code above shows that the Activity is responsible for displaying the response events and request results of the View UI. The above Code seems to be okay, but considering the scalability and maintainability of the Code, writing code has the disadvantages: When the View display requirement of the customer changes, we have to modify the code in the Activity to modify the View display. When the page shows that the modification is large, the code in the Activity is also greatly modified, which leads to bloated Activity code and is not conducive to maintenance, it is also very likely that other part of the code in the Activity fails when modifying the Activity. Therefore, we do not advocate writing View Interface display in the Activity. Based on the MVC design pattern development, View views are separated to relieve the burden on the Activity and enable the Activity to assume the Controller role. See the code implementation as follows:

View the project directory structure

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: display the weather information to View * User: xjp * Date: 2015/6/3 * Time: */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 ();}/*** initialize 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 (loading weather ...); activity. findViewById (R. id. btn_go ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {loadingDialog. show (); iRequest. sendRequest (cityNOInput. getText (). toString (). trim () ;}}) ;}/ *** display result ** @ 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 ();}/*** hide progress dialog box */public void hideLoadingDialog () {loadingDialog. dismiss ();}}

The View interface control is introduced into a DisplayWeatherInfoView class, which implements the initialization of View search and display of View Interface results, as well as the interface for View response events. All interface operations are in this class.

Controller

Next, let's take a look at how the Activity calls the DisplayWeatherInfoView class.

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 attributes. 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, failed to get weather information, Toast. LENGTH_SHORT ). show ();}}

The code above shows that the Activity holds the DisplayWeatherInfoView object reference and implements the RequestWeatherView control to respond to the event interface. When a user clicks a response event in the View, the Activity is notified through interface communication. The View responds to the event and the Activity is processed accordingly, in this case, the Activity acts as the Controller to send the user's Response Request to the model layer and let the model layer process network requests. Therefore, the Activity simultaneously holds the model object to reference WeatherModelImpl.

Model

Let's take a look at the WeatherModelImpl code implementation.

Package com. xjp. androidmvcdemo. model;/*** Description: Request network data interface * User: xjp * Date: 2015/6/3 * Time: */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: This interface is used to obtain weather information from the network. * User: xjp * Date: 2015/6/3 * Time: 15: 40 */public class WeatherModelImpl implements WeatherModel {@ Override public void getWeather (String cityNumber, final OnWeatherListener listener) {/* data layer operation */VolleyRequest. newInstance (). newGsonRequest (http://www.weather.com.cn/data/sk/ + cityNumber +. html, Weather. class, new Response. listener
  
   
() {@ 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 ();}});}}
  

The code above shows that a WeatherModel interface is designed here, and then the WeatherModelImpl class is implemented. The controller activity calls the method in the WeatherModelImpl class to initiate a network request, and then implements the OnWeatherListener interface to obtain the results of the network request. Then the activity continues to call displayView in DisplayWeatherInfoView. displayResult (weather); Method to display the network request results to the View interface. At this point, the activity acts as contronler to complete the coordination between the model and view.

Why is it not directly designed as a getWeather () method in the class to directly request network data? You should consider this situation: the network requests in the Code are implemented using the Volley framework. If the boss wants you to use the Afinal framework to implement network requests someday, how can you solve the problem? Is it the implementation of modifying the getWeather () method? No. This modification not only damages the previous code, but also is not conducive to maintenance. Considering the extension and maintainability of the Code in the future, we chose the interface design method to solve a problem, we implement another WeatherModelWithAfinalImpl class that inherits from WeatherModel and overwrites the method in it. This not only preserves the previous WeatherModelImpl class request network method, but also adds the WeatherModelWithAfinalImpl class request method. No modification is required for the Activity call code.

MVC usage Summary

Using the MVC design pattern, this small weather forecast project has good scalability and maintainability. When you need to change the UI display, you do not need to modify the contronler Activity code and Model) the business logic code in the WeatherModel model separates the business logic from the interface display.

In the Android project, business logic and data processing have assumed the role of Model, XML interface display, View, and Activity as the controller. The Controller acts as an intermediate Bridge. It communicates with views and models through interface communication.

When is the MVC design pattern applicable? Of course, a small project does not need to be designed using the MVC framework without frequent modifications. Instead, it feels that the code is over-designed and the code is bloated. Generally, in large projects, the business logic processing is complicated, and there are many page displays. It is advantageous to use MVC for projects that require modular design.

Advantages of MVC:

(1) low coupling. Coupling is the degree of association between module codes. Using the MVC Framework, the View layer and the Model layer can be well separated, which achieves the goal of decoupling, so the coupling is low, reduce the interaction between module codes.

(2) good scalability. Due to low coupling, you can add more code to reduce the number of code changes and reduce the bug occurrence rate.

(3) clearly divided responsibilities of the module. It is mainly divided into three modules: M, V, and C, which facilitates code maintenance.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.