MVP Architecture in Android development

Source: Internet
Author: User

Written in front, this blog originates from the public article: http://mp.weixin.qq.com/s?__biz=MzA3MDMyMjkzNg==&mid=402435540&idx=1&sn= 1cd10bd9efaac7083575367a8b4af52f&scene=1&srcid=0910arzppbvvypi1ndbznixa#wechat_redirect

More and more people are starting to talk about architecture recently. The same is true of my colleagues and engineers around me. Although I'm not particularly into MVP and DDD, our new project has decided to build on the MVP.

This article was summed up in my research and study of various articles and thematic discussions, including the following points:

    • Why are more and more people starting to focus on architecture?

    • First of all, what is MVP?

    • What kind of architecture is best, MVC,MVVM or MVP?

    • The pros and cons of MVP

    • Show me the code!!! Code Show

Unfortunately, this article will not include:

    • Detailed and Vivid code examples

    • How to write test code

Finally, I'll show you how to learn more about these topics.

Incidentally, I spoke at a local seminar last week about the MVP architecture. This article is similar to the content of the speech at that time.

(Translator Note: Read more please click on the original author PPT)

Introduction ~activity is God class ~

First, let's think about why it's so urgent to need a clear software architecture in Android development.

This paragraph is excerpted from "Code Encyclopedia second Edition":

Avoid creating divine classes. avoid creating All-knowing, omnipotent God classes. If a class takes time to retrieve data from other classes through get () and set (that is, it needs to drill into the business and tell them how to do it), then whether these functional functions should be better organized into other classes rather than God classes. (Riel 1996)

The maintenance costs of God's class are high, and it's hard to understand what's going on, and it's hard to test and scale, which is why you avoid creating the golden rule of God's class.

However, in Android development, activity classes tend to grow larger if you don't consider architectures. This is because, in Android, view and other lines are allowed to Cheng within the activity. The biggest problem is the presence of both business logic and UI logic in the activity. This increases the cost of testing and maintenance.

Activity is God.

This is one of the reasons why you need a clear architecture. Not only does the activity become bloated, but it also causes other problems, such as the complexity of the life cycle of activity and fragment, and data binding.

What is an MVP?

MVP represents Model,view and presenter.

    • The view layer handles the presentation of the User events and Views section. In Android, it could be an activity or fragment class.

    • The model layer is responsible for accessing the data. The data can be remote server API, local database or sharedpreference, etc.

    • The presenter layer is a bridge that connects (or fits) view and model.

is one of the models based on the MVP architecture. View is the UI thread. The presenter is the adapter between the view and the model. UseCase or domain is responsible for acquiring or loading data from entities in the model layer. The dependency rules are as follows:

The Dependency injection

The key is that the high-level interface does not know the details of the underlying interface, or more accurately, the high-level interface cannot, should, and must not understand the details of the underlying interface, is (oriented) abstract, and is detail-hidden.

The higher interfaces don't know about the details of the lower ones

Dependency rules?

Uncle Bob's "The Clean Architecture" describes what the rules of dependency are.

The concentric circle divides the software into different regions, generally, with the depth of the hierarchy, the higher the level of software. The outer circle is the realization mechanism, the inner circle is the core strategy.

Here is a summary of the above article:

Entities:

    • Can be an object that holds a method function

    • Can be a set of data structures or method functions

    • It doesn't matter, it can be used by different applications in the project.

Use Cases

    • Include application-specific business rules

    • Carefully orchestrate data flowing into or out of entity

    • Direct entity uses the business rules within the project scope to achieve the purpose of using case

Presenters,,controllers

    • Convert data from use case and entity to format's most convenient data

    • External systems, such as databases or Web pages, make it easy to use these data

    • MVC architecture with full GUI

External Interfaces, UI, DB

    • Where all the details are

    • such as database details, web framework details, etc.

MVC,MVP or MVVM?

So, which one is the best? Which one is better than the others? Can I just choose one?

The answer is NO.

The motives for these patterns are the same. That's how to avoid complex and confusing code, making it easy to perform unit tests and creating high-quality applications. That's it.

Of course, this is much more than the three architectural patterns. And no model can be a silver bullet, they are just one of the architectural patterns, not the only way to solve the problem. These are just methods, means, not ends, goals.

Pros and cons

OK, let's go back to the MVP architecture. We just learned what MVP is, discussed the MVP and other popular architectures, and introduced the differences between MVC,MVP and MVVM. This is a summary of the pros and cons of the MVP architecture:

* * Lee

    • Testable (TDD)

    • Maintainable (code reuse)

    • Easy Reviewe

    • Information hiding

* * Disadvantages

    • Redundancy, especially for small app development

    • Additional learning curve (possible)

    • Time costs before you start writing code (but I bet that design architecture is required for all project development)

Show me the code!!!

Only a small section of the MVP pattern is shown here. If you want to learn more about projects or vivid code examples, refer to the links and resources at the end of the article. There are very rich and well-designed examples that are basically hosted on GitHub so that you can clone, run on the device, and understand how it works.

First, define an interface for each view.

/**

* Interface classes for the Top view

*/

Public Interface TopView {

/**

* Initialize the view.

*

* e.g. the Facade-pattern method for handling all Actionbar settings

*/

void initviews ();

/**

* Open {<a href= "http://www.jobbole.com/members/57845349" > @link </a> Datepickerdialog}

*/

void opendatepickerdialog ();

/**

* Start listactivity

*/

void startlistactivity ();

}

Let's rewrite the TopView class with the following points:

    • Topactivity is only responsible for handling event monitoring or displaying each view component

    • All business logic must be delegated to the presenter class

    • In MVP, view and presenter are one by one corresponding (one-to-many in MVVM)

Public class topactivity extends Activity implements TopView {

Here we use Butterknife to inject views

/**

* Calendar Title

*/

@Bind (r.id.calendar_title)

TextView Mcalendartitle;

private toppresenter mtoppresenter;

@Override

protected void onCreate (Bundle savedinstancestate) {

Super. OnCreate (savedinstancestate);

Setcontentview (r.layout.activity_top);

Butterknife.bind (this);

//Save Toppresenter instance in a Meber variable field

mtoppresenter = new toppresenter ();

mtoppresenter.oncreate (this);

}

/*

* Overrides method from the {<a href= "http://www.jobbole.com/members/57845349" > @link </a> TopView} Interfaces

*/

@Override

public void initviews () {

//Actionbar settins

//Set event listeners

}

@Override

public void opendatepickerdialog () {

datepickerfragment.newinstance (). Show (Getsupportfragmentmanager (),

Datepickerfragment.tag);

//Don't write logic here ... all logic must is passed to the Presenter

mtoppresenter.updatecalendardate ();

}

@Override

public void startlistactivity () {

startactivity (new Intent (this, listactivity. Class));

}

}

This is the presenter class, and the most important thing is that presenter is simply a bridge between the view and the model. For example, Topusecase#savecalendardate () is hidden from toppresenter details, as is the case with TopView. You don't need to care about the data structure, and you don't have to worry about how the business logic works. So you can perform unit tests on Topusecase because the business logic is separate from the view layer.

Public class toppresenter {

@Nullable

private TopView mView;

private topusecase musecase;

public toppresenter () {

musecase = new topusecase ();

}

public void onCreate (@NonNull TopView TopView) {

mView = topView;

//Here's call View ' s implemented methods

mview.initviews ();

}

public void updatecalendardate () {

forget to return if view instances is null

if (mView = = null) {

return;

}

//Here Logic comes

String datetodisplay = musecase.getdatetodisplay (Mcontext.getresources ());

mview.updatecalendardate (datetodisplay);

//Here to save date, and this logic was hidden in UseCase class

musecase.savecalendardate ();

}

}

Of course, although the business logic is implemented in the activity class, you can still perform unit tests, but it takes a lot of time and is somewhat complex. It may take more time to run the app, instead you should have leveraged the performance of the Test class library, such as Robolectric.

Summarize

There is no panacea here, and the MVP is just one solution that can be used in conjunction with other methods, as well as selectively for different projects.

Links and Resources

The Clean Architecture (translator Note: Clear architecture. –uncle Bob

Http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html

This article, written by Uncle Bob, describes how the dependency rules look and how the components between them work. The diagram I was talking about from the outset was inspired by his article, although this article was not developed for Android, but as always, there are a lot of penetrating lines in between, so it must be read.

Architecting Android ... The clean? (Translator Note: A clear architecture in Android.) )-Fernando Cejas

http://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/

I think this is the most famous and popular blog to explore how to apply the MVP architecture to Android development topics. I also stumbled upon the term "MVP" from his easy-to-read, well-written blog. His sample code is hosted on GitHub to clone the Android developer who wants to apply the MVP architecture to the official app.

Android Architecture (Translator Note: Android architecture) –thanos Karpouzis

Https://medium.com/android-news/android-architecture-2f12e1c7d4db#.7ch5tkkx0

A simple guide to using MVC,MVP,MVVM in Android projects. I learned a lot from his ordinary but extraordinary article, especially the difference between MVC,MVP and MVVM.

Software Design Patterns on Android 中文版 (translator note: Software in Android development mode) –pedro Vicente Gómez Sánchez

Http://www.slideshare.net/PedroVicenteGmezSnch/software-design-patterns-on-android

This is a senior Android development engineer working at Karumi, who explained some of the design patterns in the MVP architecture (e.g., rendering mode, warehouse mode, and command mode). If you want to get a deeper understanding of MVC or MVP, that's what you're looking for.

M?—? Model in MVC, MVP, MVVC in Android (translator Note: The model layer in the MVC,MVP,MVVC architecture is defined in Android) –artem Zinnatullin

https://medium.com/@artem_zin/m-model-from-mvc-mvp-in-android-flow-and-mortar-bd1e50c45395#.82qjulegz

If you do not also understand the JSON and SQL in the model layer, or do not have a thorough understanding of the model layer's image models, this article will take you further to understand what the model layer is and why the model layer is independent of the other layers. The "Model Layer is Solution" section is a good explanation of how to write tests in an interface-oriented way.

MVP Architecture in Android Development (RPM)

Related Article

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.