MVP development model in Android apps

Source: Internet
Author: User

The so-called MVP (Model-view-presenter) mode. is to divide the app's structure into three layers:

View-ui Display Layer

The view layer is primarily responsible for:

    1. Provide UI interaction
    2. Modify the UI under presenter control.
    3. The business event is referred to presenter for processing.
      Attention. The view layer does not store data and does not interact with the model layer.
Presenter-Logic processing layer

The presenter layer is mainly responsible for:

    1. Handle the various business events of the UI accordingly. Maybe it's interacting with the model layer, maybe doing some calculations yourself, maybe controlling the background Task,servic
    2. Respond to various subscription events and modify the UI.
    3. Temporarily stores page-related data.
      Attention. The view reference does not appear in the presenter.
Model-Data layer

The model layer is primarily responsible for:

    1. Read and write data from data sources such as networks, databases, files, sensors, third parties, etc.
    2. Parsing the external data type into the app's internal data is handled by the upper layer.
    3. Temporary storage of data, management, coordination of data requests on the upper level.

Examples of the Activity,presenter,model are as follows:


Mvp

Divide complex functions into small problems within each layer. A single function within each layer. This makes it easy to modify extensions with Debug.
Decoupling design, independent module, more conducive to division of development and testing.

Abnormal restart of activity

The activity is restarted in a few cases by the system:

When the user rotates the screen
Not enough memory in the background
Change language Settings
Attache an external monitor and so on.

The right way should be:
The binding relationship between presenter and activity should be managed by a static class. Rather than being managed by the activity. Presenter should not be restarted when the activity is unexpectedly restarted. When the activity restarts, the presenter and activity are re-bound to restore the activity State based on the data.
And when the activity is actually destroyed. The corresponding presenter should be followed by destruction.

When memory is low, the activity is destroyed in fact the entire process is destroyed. So presenter is powerless. You need to rebuild presenter when restoring.

Life cycle

Activity is a God class, which is not really suitable as a view. So some MVP programs use activity as a presenter. The most important thing is that his life cycle involves too much logic processing business. The situation can be improved a lot if these are handled by presenter. I recommend that you implement the activity's life cycle in presenter in the top-level parent class, and then the lifecycle-related business logic is implemented directly by presenter.

Initialization of the model

Model is more than JavaBean. Model is responsible for providing various data models. On this basis I extend the model to the data layer to provide data interaction. Separate JavaBean as part of the data tier.
Each model of the model layer typically uses a single case. The advantage of this is that the only object can manage some data for use by all the upper layers.
Singleton object of Model

PublicClassUsermodelExtendsabsmodel{PublicStatic UsermodelGetInstance() {Return getinstance (Usermodel.class); }@OverrideProtectedvoidOnappcreate(Context CTX) {Super.onappcreate (CTX);Initialize}PublicvoidLogin(String number,string password,datacallback<userdetail> callback) {Make a login request and callback, and save the return account}PublicvoidRegister(String tel,string password,string Code,int gender,string Nickname,statuscallback callback) {//for registration request and callback} public void findpassword (String number,string code,string Password, Datacallback<user> callback) {//to retrieve password request and callback} public void certification (String number,string school,string realname,string stucard,datacallback<user> callback) {//authentication request and callback} public void loginout () {// Logout Operation}}                

Since the model layer manages the data, it is a singleton. He has the need for initialization, such as requesting data when the app starts, logging information, starting a background thread to synchronize information with the server, and so on. These operations are not related to presenter. is the spontaneous function of the data layer. It is necessary to initialize the model when the application is started.
But note that you cannot do too much in application's OnCreate (), or it will take too long to start. Therefore, consider creating a background thread at startup, and placing a non-immediate initialization operation on the background thread.

Treatment of Adapter

It's really hard to solve the problem of whether adapter is good for the view or presenter. But the problem is clear after the use of decoupled viewholder. The creation and alteration of views is managed by Viewholder. Then adapter only deals with logic that is oriented toward Viewholder.
Then Viewholder belonged to View,adapter belonging to presenter. Reference Easyrecyclerview
Adapter:

class PersonAdapter extends RecyclerArrayAdapter<Person> { public PersonAdapter(Context context) { super(context); } @Override public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { return new PersonViewHolder(parent); }}

Viewholder:

PublicClassPersonviewholderExtendsbaseviewholder<person> { private textview mtv_name; private simpledraweeview mimg_face; private textview mtv_sign; public  Personviewholder (viewgroup parent) {super (Parent,r.layout.item_person); Mtv_name = $ (r.id.person_name); mtv_sign = $ (r.id.person_sign); mImg _face = $ (r.id.person_face);}  @Override public void SetData (final person person) {Mtv_name.settext (Person.getname ()); Mtv_sign.settext (Person.getsign ()); Mimg_face.setimageuri ( uri.parse (Person.getface ())); }} 
RX's participation

The RX subscription release model plays a big role in MVP. Can greatly simplify the processing of inter-layer communication. View subscribes to presenter data. Presenter can subscribe data to the model layer. Form a data chain. Data can be directly linked to the view layer. Elegant and easy to expand.
Presenter

class QuestionShowPresenter extends BeamDataActivityPresenter<QuestionShowActivity,Question> { @Override protected void onCreate(QuestionShowActivity view, Bundle savedState) { super.onCreate(view, savedState); QuestionModel.getInstance().getQuestion(1).subscribe(this); }}

View

class QuestionShowActivity extends BeamDataActivity<QuestionShowPresenter,Question> { @Override public void setData(Question data) { //显示数据 } @Override public void setError(Throwable e) { //显示错误 }}
Beam

Beam is a fast development framework based on the MVP model. Reference to the nucleus. The example code above is using this (demo code for this framework for easy copying. =). Defines a set of development specifications. and provide the Activity,fragment,presenter,model based on this set of specifications such as parent classes and controls and APIs, etc., complete the application development process a lot of tedious work. And a series of optimizations. See here for details



Wen/jude95 (author of Jane's book)
Original link: http://www.jianshu.com/p/ed2aa9546c2c
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

MVP development model in Android apps

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.