On the MVP architecture in Android

Source: Internet
Author: User

To be ashamed, MVP's architecture model has been around for a year or two in Android, but it's only today that it started the MVP architecture in the Android Arena. Gossip doesn't say much, let's get started!

I. Overview of Architectural evolution

I remember when I was looking for my first job, the interviewer asked me, "How does Android belong to the MVC architecture model, briefly?" Indeed, the overall design structure of Android is the MVC design pattern, in the development of the Java EE, the use of MVC mode, MVC pattern is a classic, after decades of testing. MVC architecture in Android projects:

    • View: Is the part of the application that handles the display of data, corresponding to the layout file
    • Model: Business logic and entity model
    • Controllor: Is the part of the application that handles user interaction, and activity acts as a.

Seemingly division of labor is clear, but also brought us a lot of problems, if a page of business logic is very complex, our activty need a lot of logic to deal with code, so that activity is both like view and like Controllor, and when the father and mother, the workload is very large. The reading star that caused the code is very poor.

To solve this problem, the MVP model was born in the Android field. Add: I look at the data found that the MVP model was originally designed by Microsoft, applied in the visual Stuido platform, it must be said that Microsoft, although closed source, but very niubility.

Ii. Overview of the MVP

The above figure, a refined overview of the communication flow between MVP architectures, is in Android.

    • Model: Business logic processing, responsible for processing data loading or storage, such as from the network or local database to obtain data;
    • View: Responsible for the display of interface data, interacting with users, is activity;
    • Leader (Presenter): the equivalent of a coordinator, a bridge between a model and a view, separating the model from the view. By presenter the interaction between them, the direct interaction between M and V is isolated.

This architecture allows our activity to look more like a view, reducing the coupling between M and V.

Third, the MVP practice

Let's start by looking at our:

This is a simple answer landing page, in this landing page, we will trigger an event, that is, click the login event. Let's look at our engineering structure first.

We created: beans, model, presenter, view four packages, in order to liberate the activity, we have a lot of logic in the previous activity to split.

1. Bean Package

We created the entity Userbean to hold our user information, which is nothing to say.

     Public  class UserBean implements parcelable{        PrivateString name;PrivateString password; Public UserBean(){        } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringGetPassword() {returnPassword } Public void SetPassword(String password) { This. Password = password; }@Override         Public int describecontents() {return 0; }@Override         Public void Writetoparcel(Parcel dest,intFlags) {dest.writestring (name);        dest.writestring (password); }    }
2. View Package

We look at the view (view layer) First, view package is stored in our views layer of operations, it does not involve any business logic, mainly for our page data acquisition and Settings . For this landing function, we analyze:

    • Access to name and password
    • Save your name and password

We draw out what the Page view layer needs to do, and then we define a Iuserview interface that contains the methods we extracted.

    /**     * 抽离View层,用于View页面的数据获取之类     * @author Administrator     *     */    publicinterface IUserView {        publicgetUserName();        publicgetUserPsd();    }

We only made a fetch, did not do save. Summary: The task of the view layer is to abstract the data of the page, extracted to write the method.

3. Model Package

At the view level, our data acquisition is available and we are now working on our business logic. According to the page, we will simulate a login function, so it is a login event. We create the Iusermodel interface to contain the business logic we handle.

    /**     * 业务逻辑处理     * @author Administrator     *     */    publicinterface IUserModel {        /**         *提取的一个登陆方法,当然还可以有其它方法,比如获取数据,保存用户信息之类         * @param name  用户名         * @param pwd   密码         * @param loginListener 登陆监听         */        publicvoidlogin(String name,String pwd,ILoginListener loginListener);    }

With the interface specification of the business logic, we also need to implement it, giving us the logic we want. So there's the Usermodel class:

     Public  class Usermodel implements Iusermodel{        @Override         Public void Login(string name, string pwd, Iloginlistener loginlistener) {if(Textutils.isempty (name) | | Textutils.isempty (pwd)) {loginlistener.onerror ();return; }Try{Thread.Sleep ( the); }Catch(Interruptedexception e)            {E.printstacktrace (); }if("DSW". Equals (name) &&"123". Equals (PWD) {loginlistener.onsucess (); }Else{Loginlistener.onfail (); }        }    }

We have created an interface to judge our login events in order to facilitate our monitoring of business logic processing.

    /**     * 登陆接口的监听,方便我们在View层中控制,便于给出提示     * @author Administrator     *     */    publicinterface ILoginListener {        //登陆成功        publicvoidonSucess();        //登陆失败        publicvoidonFail();        //数据不完成        publicvoidonError();    }

We use it to monitor business processes, such as success. We pop up a toast or something.

4. Presenter Bag

The data, the business processing of the data also has, here our presenter on the Flash. Remember that it is Presenter, Presenter, Presenter (important things say three times). It is used to connect our m, v layers, allowing both to open the two-channel to achieve the entire process. Therefore, in order to achieve the relationship between the two, it will inevitably have an example of M, v. Take a look at Iuserpresenter:

     Public  class iuserpresenter {        //Data source        PrivateIuserview Userview;//Processing business logic        PrivateIusermodel Usermodel; Public Iuserpresenter(Iuserview Userview) { This. Userview = Userview; Usermodel =NewUsermodel (); }/** * Landing method, the relationship between the M,V layer is established * @param loginlistener */         Public void Login(Iloginlistener Loginlistener)        {Usermodel.login (Userview.getusername (), USERVIEW.GETUSERPSD (), Loginlistener); }    }

We just need to create a Iuserpresenter class in the activity and then call the login method to log in. In this code, Iuserview is our data source, and we use it to get the data from the page, so our activity has to implement this Iuserview interface and pass it to Iuserpresenter. Call Iusermodel in Iuserpresenter to implement the processing of the business logic.

5, the last activity processing
     Public  class mainactivity extends Activity implements Iuserview {         PrivateEditText et_name,et_pwd;PrivateButton Btn_login;//indicator interacts with the view layer        PrivateIuserpresenter Userpresenter;@Override        protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);            Setcontentview (R.layout.activity_main);            Et_name = (EditText) Findviewbyid (r.id.et_name);            Et_pwd = (EditText) Findviewbyid (R.ID.ET_PSW);            Btn_login = (Button) Findviewbyid (R.id.btn_login); Userpresenter =NewIuserpresenter ( This); Btn_login.setonclicklistener (NewOnclicklistener () {@Override                 Public void OnClick(View v)                {Userpresenter.login (Loginlistener);        }            }); }@Override         PublicStringGetUserName() {returnEt_name.gettext (). toString (); }@Override         PublicStringGETUSERPSD() {returnEt_pwd.gettext (). toString (); }/** * Login Monitor interface * /        PrivateIloginlistener Loginlistener =NewIloginlistener () {@Override             Public void onsucess() {Toast.maketext (Getapplication (),"Successful Landing", Toast.length_short). Show (); }@Override             Public void Onfail() {Toast.maketext (Getapplication (),"Login Failed", Toast.length_short). Show (); }@Override             Public void OnError() {Toast.maketext (Getapplication (),"The data is incomplete, please re-enter", Toast.length_short). Show ();    }        }; }

In activity, we implement the Iuserview interface to achieve the data acquisition of the view layer. Then create the Iuserpresenter class and call the login method to log in. At the same time realize the processing of business logic monitoring.

At this point, we have completed the entire process to see our:

It is strongly recommended that you manually tap the code to deepen your understanding.

Summary chart:

==========================================================
Mr_dsw

Reprint annotated source, sharing is the source of progress.

==========================================================

On the MVP architecture in Android

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.