Framework pattern MVC and MVP application in Android

Source: Internet
Author: User

Many people do not consider architectural patterns when developing Android projects, so that as the project grows, the code in Activty or fragment will become more and more, resulting in a more complex maintenance of the project. However, using more than one of the two frameworks in Android is MVC and MVP, and I'll describe each of these two framework patterns.

First, the MVC framework pattern

The full name of MVC is the model View Controller, which is the abbreviation for the models-view-controller, a software design paradigm that organizes the code with a method of business logic, data, and interface display separation. Aggregating business logic into a single component does not require rewriting business logic while improving and personalizing the interface and user interaction. where m-layer processing data, business logic, and so on; v-Layer processing interface display results; The C-layer acts as a bridge to control the V-layer and M-layer communication to achieve the separation view display and the business logic layer.

In fact, MVC in the development of Java EE is a lot of applications, it separates the business logic and interface, through the controller to connect it, so as to achieve a good decoupling effect, through the code compiled by MVC is conducive to later maintenance and transformation.

in Android development, we also often see the image of the MVC framework pattern, such as when we develop the Android application, the interface is written in XML, and we often back to the network access data independent, and then through the activity to deal with user interaction problems, This is a kind of MVC idea. the advantage of using the MVC pattern is that it facilitates the display and business logic of the UI interface and separates data processing. The following is a detailed description of the MVC expression:

m layer: Suitable for some business logic processing, such as Database Access Operations, network operations, complex algorithms, time-consuming tasks, etc. are handled in the model layer.

V Layer: The portion of the application layer that handles the display of data, and the XML layout can be treated as a V-layer, showing the data results of the model layer.

Layer C: In Android, activity handles user interaction issues, so you can think of activity as a controller, Activity reads data from the V-view layer (eg. reads data from the current EditText control), controls user input (input to the Eg.edittext control data), and sends data requests to model (eg. initiating a network request, etc.).

To make it easy to understand, let me give you an example, because MVC is easy to understand, and because of the space problem, here is just a short pseudo-code, because the code is meaningless:

We interpret MVC for Android through a small project that gets the weather forecast data.

Controller controllers

public class Mainactivity extends Activity implements Struidatalistener {private Strvoll    Eyinterface Networkhelper;    Private Strvolleyinterface Expertnetworkhelper;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); }//load network data private void Initdate () {try {networkhelper = new Strvolleyinterface (demanddetailacti            Vity.this);            Networkhelper.setstruidatalistener (Demanddetailactivity.this);        Apiclient.getdatadetail (demanddetailactivity.this, ID, networkhelper);        } catch (Exception e) {e.printstacktrace (); }} @Override public void ondatachanged (String data) {//Data loaded successfully//.... Update UI} @Override public void onerrorhappened (Volleyerror error) {Toast.maketext (demanddetailactivity.this , "Load error, please check the network!"    ", Toast.length_short). Show (); }}

As you can see from the code above, the activity holds the object of the Apiclient network request model, and when we need to get the data, we only need to call the InitData () method. For example, if we click button,activity as controller control layer will process the View view layer, and call the Apiclient.getdatadetail method, when the model models processing data end, through the interface ondatachanged notify the view Layer data processing finished, the View view layer to update the interface UI. Then the view layer to update the interface. See here, we will find the entire MVC framework process is reflected in the activity.

Model Models

Here apiclient is the model layer, specifically for processing network data requests, the code will not show, the reader just understand the line.

In the example above, activity separated the view view display from the Model data processing. Activity acting as Contronller completed the coordination between model and view.
So why do we do this, is it not more convenient to implement the tennis request directly in the activity?

Many people may have this kind of doubt, but people think, if this network request is implemented in activity, one is not conducive to code reuse, but later maintenance is very difficult. For example, our current network request is volley, later want to replace nohttp implementation, we need to modify each activity class, this is not very cumbersome, see here we will find the benefits of MVC.
A brief summary of MVC:

In the Android project, the business logic, data processing, etc. served as the Model (modeling) role, the XML interface display, and so on as the view (view) role, activity as the Contronller (Controller) role. The Contronller (Controller) is the role of an intermediate bridge, which works through interface communication to coordinate view (view) and model (models), and plays a role in communication between the two.

We found that, in fact, the controller activity is mainly decoupled, the view view and model models are separated, although the activity plays an interactive role, but there is a lot of activity in the View UI display code, Therefore, the view view and the activity controller are not completely detached, meaning that part of the view and Contronller controller activity is bound to a class. So MVC is not perfect for the decoupling effect of Android, and when our app gets bigger, we'll also find that our activity and fragment will grow larger.

So if we are developing an Android project is not very large, with the MVC framework model is relatively ideal, if our project is relatively large, and often need to modify maintenance later, I would recommend using the MVP framework model, the following for the MVP framework model to do a simple introduction.

Second, MVP framework model

What is MVP?

MPV has evolved from the classic MVC model, and its basic ideas are interlinked.

The MVP is the abbreviation for the model, view, controller (Presenter), which represents 3 different modules in the project, respectively.

Model: is responsible for processing data loading or storage, such as from the network or local database to obtain data;

View: Responsible for the display of the interface data, interacting with the user;

Controller (Presenter): the equivalent of a coordinator, a bridge between a model and a view, separating the model from the view.

In the Andorid project, we are accustomed to use activity as a controller in MVC to achieve model and view separation, but in the MVP framework mode, activity is usually used as the view layer, Because the activity and the view view display are closely related in the MVC framework mode, the activity contains a lot of view display code, if the boss said the need to modify the view display, then do you feel the need to modify the activity of the large number of code? This will destroy the control logic in the activity and lead to too much responsibility in the activity. According to the principle of single responsibility, activity mainly plays the role of user interaction, that is, receiving user input, displaying the request result. Therefore, the role of activity can be mitigated by the MVP framework model.

As shown, the view and model do not interact directly, but instead use presenter as a bridge between the view and the model. Where presenter holds a reference to the Viwe layer as well as the interface of the model layer, and the view layer holds a reference to presenter layer interface. When a view layer interface needs to show some data, it first calls an interface of the presenter layer, and then the presenter layer calls the model layer to request data. When the model layer data is loaded successfully, the callback method of the presenter layer is called to notify the presenter layer that the data is loaded, and finally the interface of the presenter layer is called to display the loaded data to the user. This is the entire core process of the MVP model.

The benefit of this layering is that the coupling between the model and the view layer is greatly reduced. On the one hand, the view layer and the model layer can be independently developed and tested. On the other hand, the model layer can be encapsulated and reused, which can greatly reduce the amount of code. Of course, there are some other advantages of MVP, which are not mentioned here. Let's look at the use of MVP mode in specific projects.

I'll give you an example of getting the weather so it's easy for everyone to read

Model Models

/** * Weather model Interface */public interface Weathermodel {void Loadweather (String cityno, Onweatherlistener listener);} .../** * Weather model implementation */public class Weathermodelimpl implements Weathermodel {@Override public void Loadweather (String Cityno, final Onweatherlistener listener) {/* data-tier operation */Volleyrequest.newinstance (). Newgsonrequest ("http://www.weather.com.cn/data/sk/" + Cityno + ". htm"                    L ", Weather.class, New response.listener<weather> () {@Override public void Onresponse (Weather Weather) {if (Weather! = null) {Listen                        Er.onsuccess (weather);                        } else {listener.onerror (); }}, new Response.errorlistener () {@Override PU            Blic void Onerrorresponse (volleyerror error) {listener.onerror ();        }                }); }}

Like MVC, the Model code does not change, just use and process the network request, and after the request succeeds the interface callback returns the data processed by the model to the presenter controller.

Presenter Controller

/** * Weather presenter Interface */public interface Weatherpresenter {/** * get weather logic */void GetWeather (String cityno);     } .../** * in the presenter layer, to the model layer callback, change the state of the view layer, to ensure that the model layer does not directly manipulate the view layer */public interface Onweatherlistener {/**    * Callback When successful * * @param weather */void onsuccess (weather weather); /** * Failure callback, simple processing, did not do what */void OnError (); }........./** * Weather presenter Implementation */public class Weatherpresenterimpl implements Weatherpresenter, Onweatherlistener {/*p    Resenter as the middle layer, holding the view and model references */private Weatherview Weatherview;     Private Weathermodel Weathermodel;        Public Weatherpresenterimpl (Weatherview weatherview) {this.weatherview = Weatherview;    Weathermodel = new Weathermodelimpl ();        } @Override public void GetWeather (String cityno) {weatherview.showloading ();    Weathermodel.loadweather (Cityno, this);        } @Override public void onsuccess (Weather Weather) {weatherview.hideloading (); WeatHerview.setweatherinfo (weather);        } @Override public void OnError () {weatherview.hideloading ();    Weatherview.showerror (); }}

From the code we can see that the presenter Controller holds both Weathermodel and Weatherview objects and implements the Onweatherlistener interface to retrieve the model data, so Weatherpresenterimpl sends a data request to Weathermodel and then obtains the request result through the Onweatherlistener interface. The data is displayed in the view view of the activity as the result of the interface Weatherview. In order to completely separate the model and view, imagine that in this case, if you need to modify the model is not affected by the view code changes, in the same vein, when modifying the view layer, there is no need to modify the model layer. The equivalent model and view do not know each other's existence, is through the intermediary controller presenter to communicate.

View views

First define a View view display interface Weatherview

The News list module mainly shows the news list information obtained from the network, and the interface of the view layer probably needs the following methods:

(1) in the process of loading the data, you need to prompt "loading" Feedback information to the user

(2) After the load is successful, the loaded data is populated to Recyclerview display to the user

(3) After a successful load, the "Loading" feedback message needs to be canceled

(4) If the load data fails, if no network connection, you need to give users prompt information

As described above, we define the interface of the view layer as follows, corresponding to the above four methods:

Public interface Weatherview {    void showloading ();     void Hideloading ();     void ShowError ();     void Setweatherinfo (Weather Weather);}
then implement the activity to implement the Weatherview interface
/** * Weather interface */public class Weatheractivity extends Baseactivity implements Weatherview, View.onclicklistener {...     .... private weatherpresenter weatherpresenter;;; ";".        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);     Init (); } private void Init () {<span style= "white-space:pre" &GT;&LT;/SPAN&GT; .... Findview (R.ID.BTN), and so on.         _go). Setonclicklistener (this); Weatherpresenter = new Weatherpresenterimpl (this);        Incoming Weatherview Loadingdialog = new ProgressDialog (this);    Loadingdialog.settitle ("Loading in the weather ..."); } @Override public void OnClick (View v) {switch (V.getid ()) {R.id.btn_go:w                Eatherpresenter.getweather (Citynoinput.gettext (). toString (). Trim ());        Break    }} @Override public void showloading () {loadingdialog.show (); }     @Override public void hideloading () {Loadingdialog.dismiss ();  } @Override public void ShowError () {//do something Toast.maketext (Getapplicationcontext (), "error",    Toast.length_short). Show ();        } @Override public void Setweatherinfo (Weather Weather) {weatherinfo info = weather.getweatherinfo (); Update the interface ........... ...} }
Summary:

The MVP framework model completely separates the model and view views, which makes the code less coupled and uses the MVP framework to write the project to achieve decoupling. The biggest difference between MVP and MVC is that the V and C relationships in MVC are tight, the coupling is too high, and accessing m from C can be seen as accessing m from V to some extent. And the MVP in the M and V completely separate, do not know each other's existence, presenter through the interface Communication mode V and M communication. In Android, the MVP framework activity serves as the View view layer, and the MVC framework Mode activity acts as a controller.

Although the MVP can achieve a good decoupling effect, but in the process of development need to write a layer (Presenter) of code, the amount of code will be expanded, and business logic for the less familiar developers is still slightly complicated, so it is recommended that if the development of relatively small projects, And the project does not need frequent changes can choose MVC, if the development of relatively large projects, and the need to continue to maintain the changes later, the proposed use of MVP framework model development.


Framework pattern MVC and MVP application in Android

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.