MVP of App Architecture learning

Source: Internet
Author: User

The app has a good architecture that brings the following benefits: Easy to extend, easy to maintain. If an app does not have a good architecture, then the coupled code will appear everywhere. Without an architecture, then, the code would be all sorts of confusion, and I'm deeply aware of it.

Confusion, it seems that the problem is not big, for small-scale apps, because, I still can spend time to read it. However, as the app becomes more and more functional, every time you add a feature or modify a feature, you'll find: 1. You do the functions and functions that you did before, there are duplicate codes. 2. It is difficult for you to modify a function quickly and correctly, because the code is too coupled because the code hierarchy is unclear.

In short, past experience has taught me that it's good to have an app that is architected, layered, and then developed in a well-defined architectural pattern. After I have determined the importance of architecture, then of course it is learning it.

The architecture pattern I'm learning today is MVP.

MVP mode:

A software is divided into three layers, view layer, presenter layer, model layer.

The function of the view layer is to display the interface and draw the interface.

The responsibility of the presenter layer is to implement various business logic, and the code for the business logic is placed on this layer.

The role of the model layer is to store, modify, and retrieve data.

interactions between the layers:

The communication between the view layer and the presenter layer is bidirectional.

The communication between the presenter layer and the model layer is bidirectional.

The view layer does not interact with the model layer.

MVP mode app to Android app:

View layer: Activity,fragment, where the interface is displayed, is the content of the view layer.

Presenter layer: Click on a button to execute the business logic, it is implemented by the presenter layer. That is, presenter layer abstraction, extract the business logic in the activity,fragment. This allows you to decouple the business logic code from the interface presentation code. Business logic can be reused.

Model layer: This layer is the data access, data modification layer. configuration information, obtaining data from the data source, obtaining server data, obtaining data from the database, and updating the database data, which are provided by this layer.

An example analysis of the MVP model applied to Android app:

Example analysis: 1. What to do on each layer, declare it well with the interface. 2. When the interface is declared well, it is implemented with the actual class. such as the login interface: 1. To determine the login interface, its view of what behavior. 2. The business logic implementation of the login interface is done by invoking the presenter layer method. 3.presenter and view are communicating with each other.

Login This module to put the view layer and the presenter layer together:

Package com.antonioleiva.mvpexample.app.Login;

Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.EditText;
Import Android.widget.ProgressBar;

Import COM.ANTONIOLEIVA.MVPEXAMPLE.APP.R;
Import com.antonioleiva.mvpexample.app.main.MainActivity;

public class Loginactivity extends Activityimplements LoginView, View.onclicklistener {

Private ProgressBar ProgressBar;
Private EditText username;
private EditText password;
Private Loginpresenter presenter;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_login);

ProgressBar = (ProgressBar) Findviewbyid (r.id.progress);
Username = (EditText) Findviewbyid (r.id.username);
Password = (EditText) Findviewbyid (R.id.password);
Findviewbyid (R.id.button). Setonclicklistener (this);

presenter = new Loginpresenterimpl (this);
}

@Override public void ShowProgress () {
Progressbar.setvisibility (view.visible);
}

@Override public void hideprogress () {
Progressbar.setvisibility (View.gone);
}

@Override public void Setusernameerror () {
Username.seterror (getString (r.string.username_error));
}

@Override public void Setpassworderror () {
Password.seterror (getString (r.string.password_error));
}

@Override public void Navigatetohome () {
StartActivity (New Intent (this, mainactivity.class));
Finish ();
}

@Override public void OnClick (View v) {
Presenter.validatecredentials (Username.gettext (). ToString (), Password.gettext (). ToString ());
}
}

First, the view layer and presenter interaction: view to Presenter call (View--->presenter):The above code, when the user clicks the button, will execute an account and password Authentication business logic. This business logic is encapsulated in the presenter. We call presenter's Validatecredentials method, pass parameters, and execute the business logic of account and password verification. The benefit of encapsulating business logic to the presenter layer is that we can reuse a business logic anywhere. For example, this validatecredentials business logic can be reused. presenter to view call (Presenter--->view):When instantiating presenter, provide a LoginView implementation. Public Loginpresenterimpl (LoginView LoginView) {
This.loginview = LoginView;
This.logininteractor = new Logininteractorimpl ();
Then, the LoginView interface defines the various behaviors. Presenter implements presenter control of the view by invoking the behavior provided by LoginView. Here, when validating, there will be different situations, for different situations, the presenter layer will call LoginView in different ways, to inform the user of the current validation results. As follows: @Override public void Onusernameerror () {
loginview.setusernameerror ();
loginview.hideprogress ();
} @Override public void Onpassworderror () {
loginview.setpassworderror ();
loginview.hideprogress ();
} @Override public void onsuccess () {
loginview.navigatetohome ();
} 1). Business logic Implementation of the presenter layer: the presenter layer has only one business logic, which is declared by the interface Loginpresenter interface:Public interface Loginpresenter {
public void Validatecredentials (string username, string password);
} public class Loginpresenterimpl implements Loginpresenter, Onloginfinishedlistener {

Private LoginView LoginView;
Private Logininteractor Logininteractor;

Public Loginpresenterimpl (LoginView LoginView) {
This.loginview = LoginView;
This.logininteractor = new Logininteractorimpl ();
}

@Override public void Validatecredentials (string username, string password) {
loginview.showprogress ();
logininteractor.login (username, password, this);
    }

@Override public void Onusernameerror () {
Loginview.setusernameerror ();
Loginview.hideprogress ();
}

@Override public void Onpassworderror () {
Loginview.setpassworderror ();
Loginview.hideprogress ();
}

@Override public void onsuccess () {
Loginview.navigatetohome ();
}
Its business logic implementation is made by member Logininterator. Then, Logininterator to notify Loginpresenterimpl of the result of the decision by calling the method in the Onloginfinishedlistener interface. The Loginpresenterimpl implements the Onloginfinishedlistener interface. Communications from Logininteratorimpl to Loginpresenterimpl (logininteratorimpl--->loginpresenterimpl):The Onloginfinishedlistener interface, which defines the behavior that Loginpresenterimpl can be called by Logininteratorimpl, is used to inform the results of Loginpresenterimpl validation. Public interface Onloginfinishedlistener {

public void Onusernameerror ();

public void Onpassworderror ();

public void onsuccess ();
} public class Logininteractorimpl implements Logininteractor {

@Override
public void Login (final string username, final string password, final Onloginfinishedlistener listener) {
Mock Login. I ' m creating a handler to delay the answer a couple of seconds
New Handler (). postdelayed (New Runnable () {
@Override public void Run () {
Boolean error = FALSE;
if (Textutils.isempty (username)) {
listener.onusernameerror ();
Error = TRUE;
}
if (textutils.isempty (password)) {
listener.onpassworderror ();
Error = TRUE;
}
if (!error) {
listener.onsuccess ();
}
}
}, 2000);
}
} Communication from Loginpresenterimpl to Logininteratorimpl ( Loginpresenterimpl---> logininteratorimpl ):@Override public void Validatecredentials (string username, string password) {
Loginview.showprogress ();
logininteractor.login (username, password, this);
} Second, view layer:The current activity implements the LoginView interface, so the current activity is LoginView, as the view layer. It defines the behavior for presenter calls. Public interface LoginView {
public void showprogress ();

public void hideprogress ();

public void Setusernameerror ();

public void Setpassworderror ();

public void Navigatetohome ();
}--------------------------------------------------------------------- Main module First, view layer:Public interface MainView {

public void showprogress ();

public void hideprogress ();

public void Setitems (list<string> items);

public void ShowMessage (String message);
These are the methods that are called for the presenter layer. The code in these methods is related to the interface display. view layer to presenter layer of communication, and the implementation of the view layer:public class Mainactivity extends Activity implements MainView, Adapterview.onitemclicklistener {

Private ListView ListView;
Private ProgressBar ProgressBar;
Private Mainpresenter presenter;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
ListView = (ListView) Findviewbyid (R.id.list);
Listview.setonitemclicklistener (this);
ProgressBar = (ProgressBar) Findviewbyid (r.id.progress);
 presenter = new Mainpresenterimpl (this);

}

@Override protected void Onresume () {
Super.onresume ();
Presenter.onresume ();
}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}

@Override
public boolean onoptionsitemselected (MenuItem item) {
Handle Action Bar Item clicks here. The Action Bar would
Automatically handle clicks on the Home/up button, so long
As you specify a the parent activity in Androidmanifest.xml.
int id = item.getitemid ();
if (id = = r.id.action_settings) {
return true;
}
return super.onoptionsitemselected (item);
}

@Override public void showprogress () {
Progressbar.setvisibility (view.visible);
Listview.setvisibility (view.invisible);
}

@Override public void hideprogress () {
Progressbar.setvisibility (view.invisible);
Listview.setvisibility (view.visible);
}

@Override public void Setitems (list<string> items) {
Listview.setadapter (New arrayadapter<string> (this, Android. R.layout.simple_list_item_1, items));
}

@Override public void ShowMessage (String message) {
Toast.maketext (this, message, Toast.length_long). Show ();
}

@Override public void Onitemclick (adapterview<?> parent, view view, int position, long ID) {
presenter.onitemclicked (position);
}
The red part is the behavior of Mainview, which is the code of the interface display. The blue section is the implementation of the view layer to Presenter communication (View--->presenter). second, presenter layer:Public interface Mainpresenter {

public void Onresume ();

public void onitemclicked (int position);
It has two business logic to implement, one is Onresume (), and the other is onitemclicked (int position). presenter layer to view layer of communication, and the implementation of the presenter layer:public class Mainpresenterimpl implements Mainpresenter, Onfinishedlistener {

Private MainView MainView;
Private Finditemsinteractor Finditemsinteractor;

Public Mainpresenterimpl (MainView MainView) {
This.mainview = MainView;
Finditemsinteractor = new Finditemsinteractorimpl ();
}

@Override public void Onresume () {
mainview.showprogress ();
Finditemsinteractor.finditems (this);
}

@Override public void onitemclicked (int position) {
Mainview.showmessage (String.Format ("Position%d clicked", Position + 1));
}

@Override public void onfinished (list<string> items) {
mainview.setitems (items);
Mainview.hideprogress ();
}
The red part is the communication implementation of the Presenter layer to the View layer (Presenter--->view). The Onresume () method and the onitemclicked (int position) method are the business logic that presenter implements. Where the Finditemsinteractor member is responsible for creating a list implementation. Reference: Http://antonioleiva.com/mvp-android/

MVP of App Architecture learning

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.