MVP mode from beginner to proficient

Source: Internet
Author: User
Tags abstract regular expression

First attach yourself to an MVP demo, which is a very standard Mvp,github address as follows:

Https://github.com/SilasGao/MVPDemo


First of all, the MVP evolved from the classic MVC architecture, so we have to say what is the MVC pattern first.

System c/S (client/server) three-tier architecture model:

1) View layer: The general use of XML file to the application of the interface description, the use of the time can be directly introduced, extremely convenient, can greatly shorten the development time, can also use javascript+html and other ways as the view layer, Of course, there is a need for communication between Java and JavaScript, and fortunately, Android provides a very convenient communication implementation. Business Logic Layer (BLL): Its focus is mainly on the development of business rules, the implementation of business processes and other business requirements related to the system design, that is, it is related to the domain of the system (domain) logic, and many times, the business logic layer is also called the domain layer.

2) control layer (Controller): The task of Android control layer usually falls on the shoulders of many acitvity, this phrase also implies do not write code in acitivity, want to through activity delivery model business Logic layer processing.

3) Model: the operation of the database, as well as other data-related operations should be processed in the model, of course, business calculations and other operations must be placed in the layer. is the binary data in the application.

The interaction and function of the three-tier architecture three layer is shown in the following figure:


The traditional MVC pattern is very good and we are familiar with it after all these years. (Suddenly thought to go to a company interview he asked a Helloword Android project is not MVC, I said no, he said answer wrong, assi it.) )

On the Android project you will find that the activity is too much of a responsibility and everything is in the activity, resulting in the activity being too bloated. Although can be pumped out, but will find the code is still a lot, think of thousands of lines of code has not commented, can not faint. Even if you write, some days to see also some dizzy it?

In particular, the code is finished, one months after the need to change, from 600, 700 lines of code to find the place to modify is a bit of effort.

To relieve the stress of activity, the MVP appeared.


What are the benefits of MVP, and why use MVP?

Online search of a large number of MVP benefits, I summarize the following main points:

Code decoupling structure Clear
Reusable scalability for unit testing in MVP view does not use model directly, the communication between them is through presenter (Controller in MVC), all interactions occur inside presenter, In MVC, view reads data from the direct model rather than through the Controller.
In the MVP, presenter completely separates the model from the view, and the main program logic is implemented in presenter. Moreover, the presenter is not directly related to the specific view, but interacts through the interface, so that the presenter can be kept unchanged when the view is changed, and can be reused multiple times. In the MVP, the logic of the application is mainly implemented in presenter, where the view is very thin layer, only should have a simple Set/get method, user input and Settings interface display content, in addition to this should not have more content, never allow direct access to model. MVP is the main solution is to pull the logic layer into the P-layer, if the requirements of the logical changes can only need to modify the P-layer or the logical change we can directly rewrite a p can also, a lot of developers write everything in the activity/ Fragment in this case encountered frequent changes in demand or logic more and more complex, activity/fragment inside will appear too much mixed logic leads to errors, so the MVP mode for the app to control logic and UI decoupling is a good choice.

It says that logic is handled in presenter, assuming this is a login interface, if you want to enter the account password, then the account password is empty judgment and regular expression judgment, etc. also put in the presenter, after all, these are logic. Then the judgment is successful (the following operation is done in presenter), first call the view layer method, let ProgressDialog display, and then call the model layer of the network request, the result of the presenter callback. In the callback to do progressdialog disappear processing, and then successfully call the view layer method, into the main interface. If it fails, call the view layer method, prompt for a failed toast, and so on.
This is the simplest process.

what the MVP is. How to achieve.
The following figure is the code in my demo, just a page, but a page unexpectedly has so many classes, 11, I le a go, scared the baby, so many classes, to tell the truth a class can be solved. Don't panic, let's examine why so many classes
let's start by describing what each class is for:Buybooactivity is our activity baseactivity is the base class for activity.
Basepresenter is the base class of presenter
Buybookbean is our bean, the legendary entity class, several member variables that automatically generate a bunch of get, set methods of that class Ibuybookview that is Buybooactivity interface Buybookpresenter is the Actvity presenter Ibuybookpresenter is the Buybookpresenter interface.
Buybookmodel is the data layer of the activity Ibuybookmodel is the interface of Buybookmodel
Buybookadapter is the buybooactivity inside the ListView adapter Valuecallback, is a generic callback interface where the interface starts with I, each model,presenter, and the Activity view , all correspond to an interface, some people may ask, why write interface, a little more so many classes, see all the crazy force (such as a former colleague, he has been said that the project with the MVP, but he does not know what is MVP, directly to the data layer written in the p, presumably he thought the Bean is the model bar. I do not tell him, after all, people pay higher. It suddenly reminds me of his previous MVVM pattern, the first m is the bean, he says it's model, the second m and a v he said it was ViewModel, and the result was all the network requests, the last V he put aciivty and fragment. All right, here's the joke, go ahead with our theme.
why write interfaces. The children's shoes that ask this question should review the six basic principles of design patterns, we want to control the project rather than the project control us, we are going to do is interface-oriented programming, using abstract (or interface) to build the framework, with the implementation of extension details. Of course, the interface can not be abused, we have to see the specific circumstances, here I am in accordance with the highest standards to write.

Google's official MVP example project is to put the above Ibuybookpresenter and Ibuybookview these 2 interfaces into the Ibuybookcontract this Protocol class, in fact, the same, it is a personal preference, each has its advantages and disadvantages. For example, the code of this chestnut changed to have the protocol class of this is shown in the code below, see it, is actually the same.

Public interface ibuybookcontract
{
    interface ibuybookview
    {
        void Showtoast (String msg);

        void Refreshadapter ();

        void Onempty ();
    }

    Interface Ibuybookpresenter
    {

        list<buybookbean> getadapterdata ();
    }
}


M (Model)The data layer, like m in MVC, is used to put data processing (such as network requests, caches, etc.).
V (View)Responsible for the implementation of UI specific display. For example, presenter is handing out an action that is showdialog to show the progress command, then our view is responsible for implementing the specific UI.
P (Presenter)is responsible for processing business logic code, processing model data, and then distributing the processed data to the view layer.


let's start with a code explanation .


First of all, View Ibuybookview

This is primarily a series of activity-related UI operations, which are then implemented with our activity so that presenter can be called.

Public interface Ibuybookview {
    /**
     * hint Toast
     *
    /void Showtoast (String msg);

    /**
     * Refresh Adapter
     *
    /void Refreshadapter ();

    void Onempty ();
}

Next talk ModelIbuybookmodel Buybookmodel

Mainly wrote a few methods for Buybookmodel to achieve

Public interface Ibuybookmodel {
    /**
     * Get analog data
     *
    /void Gettestdata (valuecallback<list< Buybookbean>> callBack);


    /**
     * Return local adapter Data
     * @return * *
    /list<buybookbean> getadapterdata ();
}


Here to implement the Ibuybookmodel, and then simulated the next network request, with random to simulate the success and failure of the request, so if there is a child shoes download demo found in how blank one, then please quit more than a few times, I have 5 times in a row is blank, this luck too back it.

public class Buybookmodel implements Ibuybookmodel {private list<buybookbean> listData;
    Public Buybookmodel () {this.listdata = new arraylist<> (); } @Override public void Gettestdata (final valuecallback<list<buybookbean>> callBack) {new Ha Ndler (). postdelayed (New Runnable () {@Override public void run () {List<buybook
                bean> list = new arraylist<> ();
                List.add (New Buybookbean ("Zhao Yun", 1, "09-27 09:11"));
                List.add (New Buybookbean ("Zhao Yun, next door Lao Wang, Xiao Wang, Dian Wei, mink Cicada, Lin Fang, Cao, Liu Bei, Guan Yu, Jack Huang, Zhang Fei, Zhuge Ming", 10, "09-27 09:11"));
                List.add (New Buybookbean ("Jack Huang, Sun Quan, da Jo", 50, "09-27 09:11"));

                List.add (New Buybookbean ("Big Joe, Little Joe, Marten Cicada, Sun Shangxiang", 300, "09-27 09:11"));
                Random rd = new random ();
                int N = Rd.nextint (10);
                if (N > 5) {callback.onsuccess (list); } else {CALlback.onfail ("refusal request");
    }}}, 1000);
    } @Override Public list<buybookbean> Getadapterdata () {return listData;
 }
}


This is where the callback interface is posted upstairs, where generics are used and why. For a lot of reuse.

Public interface valuecallback<t> {
    void onsuccess (T t);

    void Onfail (String code);
}

Next talk PresenterBasepresenter Ibuybookpresenterbuybookpresenter

This is the base class of all presenter, there is a InitData () method, basic each presenter to deal with the network request it, so I got a base class, and why is abstract rather than interface, this is because the abstraction convenient point, If we add a new method to an abstract class (which is not abstract), we can give him a default implementation, and do not modify the existing code, but if it is an interface, it is necessary to modify the existing code. What do we want to add here?

Why this is a generic type. In order to let a person see this presenter know this corresponds to which activity, actually this can not add, but I think add to better. It is easy for Yimeimei to change this class later.

Public abstract class Basepresenter<t extends baseactivity> {

    abstract void InitData ();
}

Here is a main method for buybookpresenter implementation

Public interface Ibuybookpresenter {

    list<buybookbean> getadapterdata ();
}


Here is the first implementation of Ibuybookpresenter inherited the Basepresenter, and then rewrite some methods. Here the construction method is the focus, in the construction method, we need to pass in a ibookview, in fact, our activity has been implemented Ibookview, so here is actually uploading the specific activity, that is this on the line. Then the model we can use directly new, here is new.

In the initdata we have made a specific network request, the network request we are not to play a dialog out, directly in this mview.loading (); Call on the line. Then the request succeeds Onsuccess () inside to let dialog disappear, reminding the adapter to refresh. Failure Words onfail () inside the hint dialog disappears, then the ListView settings Failed page or something.


public class Buybookpresenter extends basepresenter<buybookactivity> implements Ibuybookpresenter {private IBu
    Ybookview MView;

    Private Ibuybookmodel Mmodel;
        Public Buybookpresenter (Ibuybookview ibuybookview) {this.mview = Ibuybookview;
    This.mmodel = new Buybookmodel ();
    } @Override Public list<buybookbean> Getadapterdata () {return mmodel.getadapterdata (); } @Override public void InitData () {//Popup here Loading Mmodel.gettestdata (new valuecallback<list& Lt
                Buybookbean>> () {@Override public void onsuccess (list<buybookbean> buybookbeen) { Cancel loading//simple data operation can be done in presenter Mmodel.getadapterdata (). AddAll (Buybook
                Been);
            Mview.refreshadapter (); } @Override public void Onfail (String code) {//cancel loading here Mvie
  W.showtoast (code);              Mview.onempty ();
    }
        }); }
}

And then we'll talk about our activity buybookactivity baseactivity

This is the base class of our acticity, we can see that there is a generic type, note that the high energy ahead. The generic must also inherit Basepresenter, which is the first thing to know about the presenter in order to see the activity, and the next most important thing is to basepresenter the following member variable, We write an abstract method that requires the return of the generic T, and this generic T inherits the Basepresenter, then we get the specific presenter member variable, you can directly use this member variable to invoke the method in presenter.

Public abstract class Baseactivity<t extends Basepresenter> extends Activity {
    
    protected T basepresenter;

    @Override
    protected void onCreate (Bundle savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (GetLayout ());
        Initview ();
        Basepresenter = Initpresent ();
        Onprepare ();
    }

    Abstract T initpresent ();

    abstract int getlayout ();

    abstract void Initview ();

    abstract void Onprepare ();
}

This is the final concrete activity, you can see there is no logic, basically is a number of rewriting methods.

public class Buybookactivity extends baseactivity<buybookpresenter> implements Ibuybookview {
    Private ListView Mlistview;

    Private Buybookadapter Madapter;
    @Override Buybookpresenter initpresent () {return new buybookpresenter (this);
    } @Override int GetLayout () {return r.layout.activity_main;
    } @Override void Initview () {Mlistview = (ListView) Findviewbyid (R.id.listview);
        } @Override void Onprepare () {madapter = new Buybookadapter (this, basepresenter.getadapterdata ());
        Mlistview.setadapter (Madapter);
    Basepresenter.initdata (); 
    } @Override public void Showtoast (String msg) {Toast.maketext (this, MSG, Toast.length_short). Show ();
    } @Override public void Refreshadapter () {madapter.notifydatasetchanged ();
    } public void Onempty () {mlistview.setemptyview (null); }
}


Finally, although the MVP model has many benefits, one of the fatal drawbacks is that there are too many classes, which would have changed to a class of up to 7 classes, at least 6 classes (using the Contract Protocol Class). So not all the pages to use MVP mode, very simple page is not necessary, waste time is not.


Why does the MVP Model benefit unit testing?

Presenter separates the logic from the UI, which has no Android code, and is pure Java code. We can write JUnit tests directly to presenter.

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.