About the MVP architecture model

Source: Internet
Author: User

What is the MVP architecture. :

The MVP is that MODEL-VIEW-PRESENTER,MVP is evolved from the classic pattern MVC, where the basic ideas are interlinked:

Controller/presenter is responsible for the processing of logic, model provides data, view is responsible for display. As a new model, MVP and MVC have a

Significant difference: In MVP, view does not use model directly, communication between them is through presenter (Controller in MVC),

All interactions occur inside presenter, whereas in MVC, view reads data directly from the model rather than through a Controller. In MVC,

View is directly accessible to the model. As a result, the view contains the model information and inevitably includes some business logic. In the MVC model,

The model is more concerned with the same, while there are several different displays of the model, and the view. So, in the MVC model, models don't depend on view,

But view is dependent on model. Not only that, because there are some business logic implemented in the view, it is difficult to change the view,

At least those business logic is not reusable. It is clearer to explain it in the form of a flowchart:



The difference between MVP and MVC, and how MVP solves the problem of MVC.

MVP Architecture:

View: Corresponds to activity, which is responsible for drawing the view and interacting with the user

Model: Still business logic and entity model

Presenter: Responsible for completing the interaction between view and model


View does not interact directly with the model, but interacts with the model indirectly by interacting with the presenter.

The interaction between presenter and view is done through an interface.

The view is usually one-to-presenter, but complex view may bind multiple presenter to handle logic.

MVC Architecture:

View: Corresponds to a layout file

Model: Business logic and entity model

Controllor: Corresponds to activity

View can interact directly with the model.

The controller is behavior-based and can be shared by multiple view.

It is up to you to decide which view to display.

To summarize and explain is to say:

A shift from MVC to MVP is to reduce the activity's responsibilities, reduce its burden, simplify the code and some operations in the activity,

The logic code is extracted into the presenter for processing, which reduces its coupling degree.

The advantages of MVP

1. Reduce the coupling, hide the data, the activity of the code is more concise

2. Module responsibilities are clearly divided into 3. Convenient test drive development 4. Higher code reuse 5. Code flexibility


Write code based on the MVP architecture:

Let's look at the directory layer first: Here's an example of displaying a list of data.

1.View Layer:
Mainactivity.java:

public class Mainactivity extends Appcompatactivity implements Mvpview {
    private listview listview;

    @Override
    protected void onCreate (Bundle savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.activity_main);
        ListView = (ListView) Findviewbyid (r.id.lv);
        You need some way to get the data source
        new Mainacpresenter (this). Setmodel (1). Load ()
    ;

    @Override public
    void ShowData (list<string> List) {
        arrayadapter<string> arrayadapter = new Arrayadapter<string> (this, Android. R.layout.simple_list_item_1, list);
        Listview.setadapter (Arrayadapter);
    }
}

Mvpview.java
Interface interface, this interface encapsulation method is basically related to the view display.

Public interface Mvpview {public
    void ShowData (list<string> List);//update interface with data source
}


2.model Layer:

Mvpmodel.java
The encapsulation method is basically a data-related operation

Public interface Mvpmodel {
    void GetData (Onloadcompletelistener onloadcompletelistener);

    Interface  onloadcompletelistener{
        void Onloadcomplete (list<string> List);
    }
}

Mainmodel2.java:

	
public class MainModel2 implements Mvpmodel {
    @Override public
    void GetData (Onloadcompletelistener Onloadcompletelistener) {
        //Here the way changed
        list<string> List = new arraylist<> ();
        for (int i = 0; i < i++) {
            List.add ("This is the updated data" +i+ "Bar");
        }
        Onloadcompletelistener.onloadcomplete (list);
    }
}

Mainacmodel.java:

public class Mainacmodel implements Mvpmodel {
    @Override public
    void GetData (Onloadcompletelistener Onloadcompletelistener) {
        list<string> List = new arraylist<> ();
        for (int i = 0; i < i++) {
            List.add ("This is the" + i + "bar data");
        }
        if (Onloadcompletelistener!=null) {
            onloadcompletelistener.onloadcomplete (list);}}
}

The two model is written here to demonstrate two different ways of fetching data in an interface.


3.presenter Layer (CORE):
Mainacpresenter.java:
Presenter is a bridge between model and view, with some business logic in operation.

public class Mainacpresenter {
    private mvpview mvpview;
    Private Mvpmodel Mvpmodel;

    Public Mainacpresenter (Mvpview mvpview) {
        this.mvpview = Mvpview;
        This.mvpmodel = new Mainacmodel ();
    }
    Public mainacpresenter Setmodel (int model) {
        switch (model) {case
            0:
                mvpmodel = new Mainacmodel ();
                break;
            Case 1:
                Mvpmodel = new MainModel2 ();
                break;

        }
        return this;
    }


    public void Load () {
        mvpmodel.getdata (new Mvpmodel.onloadcompletelistener () {
            @Override public
            Void Onloadcomplete (list<string> list) {
			//calls the ShowData () method in mainactivity and uploads the list collection to the activity.
                mvpview.showdata (list);}}
        );
    }
}

The overall idea of the above code is: to decouple the display of the page from the data acquisition, before the MVP mode is used, all the data acquisition and interface logic

Written in the activity, this leads to the structure of the code is not clear, not easy to maintain. The core of MVP is to separate the data acquisition from the interface logic,

Three presenter to talk about the relationship between the two, and then the corresponding business logic (data + interface display) focused on the presenter layer, if a project by three

People do, you can according to this module division of labor Development, write interface to focus on the interface module, data manipulation is only concerned about the data operation module, write business logic

People can also focus on business logic, and the Division of labor is clear and does not affect each other.


But at the same time the above code still has problems, and it can't be used in real development.
Because presenter frequently needs to perform some time-consuming operations, such as requesting network data. And presenter holds a strong reference to mainactivity, if

The activity was destroyed before the request was completed, and the network request has not yet returned, causing presenter to hold the Mainactivity object, making

A memory leak occurs when the Mainactivity object cannot be reclaimed.


So how do we solve such a problem?
Our answer is to solve this problem by using weak references and activity or fragment declaration cycles. First build a presenter abstraction, we Kill

Named Basepresenter, which is a generic class.

public class Basepresenter<v extends mvpview> {
    private weakreference<v> weakreference;			The weak reference to the view interface type public

    void Attach (V mvpview) {
        weakreference = new WeakReference (mvpview);	Establish Association
    } public

    void Deattch () {
        if (weakreference! = null) {
            weakreference.clear ();
            WeakReference = null;
        }
    }

    Public V GetView () {
        return weakreference.get ();
    }
	
	public Boolean isviewattached () {
		return weakreference!=null && weakreference.get ()!=null;
	}
}
Basepresenter has 4 ways to relate to the view, disassociate it, interpret whether it is associated with view, and get a view. View type through

Basepresenter generic type is passed over, presenter holds a weak reference to the view, which is typically the view type that implements a

The type of activity or fragment for a particular interface.

Mainacpresenter modified as follows:

public class Mainacpresenter extends basepresenter<mvpview> {
    private mvpmodel Mvpmodel;

    Public Mainacpresenter () {
        Mvpmodel = new Mainacmodel ();
    }
    Public mainacpresenter Setmodel (int model) {
        switch (model) {case
            0:
                mvpmodel = new Mainacmodel ();
                break;
            Case 1:
                Mvpmodel = new MainModel2 ();
                break;

        }
        return this;
    }


    public void Load () {
        mvpmodel.getdata (new Mvpmodel.onloadcompletelistener () {
            @Override public
            Void Onloadcomplete (list<string> list) {
                GetView (). ShowData (list);}}
        );
}}


Create a baseactivity base class that controls its relationship to presenter through the Declaration period function of the base class.

Public abstract class Baseactivity<v extends Mvpview,t extends basepresenter<v>> 
	extends appcompatactivity{public

    T basepresenter;

    @Override
    protected void onCreate (@Nullable Bundle savedinstancestate) {
        super.oncreate (savedinstancestate) ;
        Basepresenter = Getbasepresenter ();
        Basepresenter.attach ((V) this);//The final this represents the specific subclass in which the subclass must implement Mvpview
    }

    @Override
    protected void OnDestroy () {
        Super.ondestroy ();
        Basepresenter.deattch ();
    }

    Public abstract T Getbasepresenter ();
}

Baseactivity contains two generic parameters, the first is the view interface type, and the second is the concrete type of the presenter. By using generic parameters, you make some

Common logic can be abstracted into the Baseactivity class. For example, in the OnCreate function of baseactivity, the Getbasepresenter () function

Create a specific presenter, the type of this presenter is the basepresenter<t> type. Call Attachview after building presenter

The number is associated with activity. In the Ondestory function, it is associated with the activity, thus avoiding a memory leak. Someone would ask if in

Ondestory the reference to the activity, it is not necessary to use the weak reference, but not in any case the OnDestroy method of activity

are called, and once this happens, a weak reference is guaranteed to not cause a memory leak.


The mainactivity in the view layer is modified as follows:

public class Mainactivity extends baseactivity<mvpview,mainacpresenter> 
	implements mvpview{

    private ListView ListView;

    @Override
    protected void onCreate (Bundle savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.activity_main);
        ListView = (ListView) Findviewbyid (r.id.lv);
        There is a way to get the data source
        Basepresenter.setmodel (1). Load ()
    ;

    @Override public
    Mainacpresenter Getbasepresenter () {
        return new Mainacpresenter ();
    }


    @Override public
    void ShowData (list<string> List) {
        arrayadapter<string> arrayadapter = new Arrayadapter<string> (this,android. r.layout.simple_list_item_1,list);
        Listview.setadapter (Arrayadapter);
    }
}

At this point, the creation of presenter and the association with the view are encapsulated into the baseactivity, eliminating the subclass duplication code and avoiding

Memory leak problem with activity. A base class like this can be established for fragment, fragmentactivity, and other types.


Big Summary:


The overall effect is that MVP is a highly recommended architectural model in the development process, which decouples the components and provides a good

Malleable, testability, stability, maintainability, at the same time make each type of responsibility relatively single, simple, to avoid the "bloated" program exists. It's thinking

Want to also very good to mention the object-oriented design principles, namely abstraction, single responsibility, minimization, low coupling.



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.