Dragon Boat Festival holiday, the weather is rainy, so at home to a blog, this blog will be for everyone to analyze the MVP model in wirelessly application.
This article will explain the MVP model in the following ways:
1. Introduction to the MVP
2. Why use MVP Mode
3. Example of MVP mode
4. Memory leak issues in MVP
1. Introduction to the MVP:
with UI the ability to create technology is growing UI more and more responsibilities are being fulfilled. To better subdivide the view and model functionality, let view focus on processing the number of and interaction with the user while allowing the Model to handle only relational data, MVP based on the MVC concept ( Model-view-presenter) mode.
in MVP mode , there are usually 4 elements:
(1) View : responsible for drawing UI elements, interacting with the user ( shown as Activity in Android );
(2) Viewinterface : requires view Implements the interface, view view interface presenter
(3) Model : responsible for storing, retrieving, manipulating data ( Sometimes a modelinterface is implemented to reduce coupling );
(4) Presenter : as a View with the Model an intermediate bond of interaction that handles the responsible logic for interacting with the user.
2. Why use MVP Mode
in theAndroidin development,Activityis not a standardMVCin the patternController,itThe primary responsibility is to load the application's layout and initialize the user interface, and accept and process the action request from the user to respond. As the complexity of the interface and its logic increases,ActivityClass ofresponsibilities are increasing so much that they become bloated. When we move the complex logic processing to another class (Presneter),Activityis actuallyMVPin the modeView, it is responsible forUIinitialization of elements, buildingUIElements andPresenterThe Association (ListenerAnd also handle some simple logic (complex logicPresenterprocessing).
Also, recall that you are developing AndroidHow does the code logic be unit tested when applied? Do you want to deploy the app every time toAndroidSimulator or on a real machine, and thenthe user operation to test? However becauseAndroidThe characteristics of the platform, each deployment takes a lot of time, which leads directly to the reduction of development efficiency. And inMVPmode, the processing of complex logicPresenteris throughInterfacewith theView (Activity)to interact with, what does that explain? Description We can implement this through a custom classInterfaceto simulateActivitythe behavior ofPresenterunit testing saves a lot of time on deployment and testing.
3. Example of MVP mode
well, after a rough look at the basic concepts of the MVP model, we'll use the MVP pattern to write a small example.
The structure of the package is as follows: Effect display:
Here's how to start with MVP mode:
1) Create the interface class for the view, based on the business definition abstract method
<span style= "FONT-SIZE:18PX;" >public interface Iuserview {//Show progress bar void showloading ();//show user data void Showuser (list<user> users);} </span>
2) Create the model's interface class, based on the business definition abstract method
One way to load the data, and set a load to complete the listener, listen to set the abstract method complete, for the completion of the callback after loading
Public interface Iusermodel {//loading user information void Loaduser (Userloadlistenner listener);//load Completed callback interface Userloadlistenner{void Complete (list<user> users);}}
3) Create the implementation class of the model, implementing an abstract method in which the user class is created on demand by the bean package
public class Usermodelimpl implements iusermodel{@Overridepublic void Loaduser (Userloadlistenner listener) {// Simulate loading local data list<user> users = new arraylist<user> () Users.add (New User ("Yao", "I am High", r.drawable.ic_launcher)) Users.add (New User ("Kobe", "Wrath 81 points", R.drawable.ic_launcher)), Users.add ("James", "I am the first in the Universe", r.drawable.ic_ Launcher) Users.add (new User ("library", "three points I strongest", r.drawable.ic_launcher)); Users.add ("Durant", "The Thousand-year-old", R.drawable.ic_launcher)); if (listener! = null) {listener.complete (users);}}
After loading the data, callback the complete method in listener.
4) Create a present, in which the constructor passes the implementation class of the view, and in which the new model implementation class is created, creates a method load that implements the bridge between the view and model communication.
public class Presenter1 {//viewiuserview Muserview;//modeliusermodel Musermodel = new Usermodelimpl ();//? Pass through the constructor to Viewpublic Presenter1 (Iuserview muserview) {super (); this.muserview = Muserview;}
Load data public void load () {//Load progress bar muserview.showloading ();//model for data acquisition if (Musermodel! = null) {Musermodel.loaduser ( New Userloadlistenner () {@Overridepublic void complete (list<user> users) {//data is loaded after the callback, Presented to view Muserview.showuser (users);}});}}
Load , call Muserview.showloading () first to display the loading progress, Then is called Musermodel.loaduser Loading data, in which to implement the Listenner complete method, wherein the logic is to use the view to display the data to the interface, the model will be the end of the callback listener in the complete method, the data is displayed on the interface.
5) The span style= "font-size:18px" > mainactivity is obviously used to display data, which has a ListView that creates two layout files associated with it activity_main.xml with Item_ User.xml, enables mainactivity to implement the Iuserview interface, and implements two abstract methods, creating the ListView adapter, overriding the constructor, and using Viewholder, reusing convertview to optimize it, finally creating presenter, and calling its L Oad method to complete loading all logic.
<pre name= "code" class= "Java" >public class Mainactivity extends Actionbaractivity implements Iuserview { private ListView Mlistview; @Override protected void onCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Mlistview = (ListView) Findviewbyid (r.id.lv); New Presenter1 (this). Load (); } public void Showuser (list<user> users) {//Display all user lists Mlistview.setadapter (new Useradapter (This,users));} @Overridepublic void Showloading () {Toast.maketext (this, "Loading in desperately", Toast.length_short). Show ();}}
Adapter:
public class Useradapter extends Baseadapter {private Context context;private list<user> users;public useradapter ( Context context, list<user> users) {this.context = Context;this.users = Users;} @Overridepublic int GetCount () {//TODO auto-generated method Stubreturn users.size ();} @Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn users.get (position);} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Layoutinflater Inflater = Layoutinflater. from (context); Viewholder Viewholder = null;//convertviewif (Convertview = = null) {Convertview = Inflater.inflate (R.layout.item_user, NULL); Viewholder = new Viewholder (); viewholder.image = (ImageView) Convertview.findviewbyid (R.id.iv_user); Viewholder.name = (TextView) Convertview.findviewbyid (r.id.tv_name); viewholder.content = (TextView) Convertview.findviewbyid (r.id.tv_content); cOnvertview.settag (Viewholder);} Else{viewholder = (Viewholder) Convertview.gettag ();} ViewHolder.image.setImageResource (Users.get (position). Getpicid ()); ViewHolder.name.setText (Users.get (position). GetName ()); ViewHolder.content.setText (Users.get (position). GetContent ()); return Convertview;} private static class Viewholder {ImageView image; TextView name; TextView content;}}
In this way, our small example is finished, the effect is as follows:
Experience the advantages of the MVP model:
A) Suppose we do not get the user data from the local, changed to get from the network, just need to write a new model implementation class, and new a present, and in the mainactivity to replace, we can solve, we simulate this situation, found that the changes are very convenient, The main interface recommends the use of the MVP mode, which adheres to the open/close principle.
b) Suppose I do not want to use the ListView to display data, want to change the GridView, do not need to modify the original code, only need to create a new activity to implement the view, implement the interface method, while using the GridView and the new one with its corresponding adapter can be, In line with the principle of open and closed, do not modify the source code, but to make extensibility changes. View and model decoupling, we can find that we write the activity inside are no model of the shadow, only presenter.
public class Gridactivity extends Mvpbaseactivity<iuserview, gridpresenter> implements iuserview{private GridView Mgridview; @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.activity_grid); Mgridview = (GridView) findViewById (R.ID.GV); Mpresenter.load ();} @Overridepublic void Showloading () {//TODO auto-generated method Stubtoast.maketext (this, "desperately loading in", Toast.length_ Short). Show ();} @Overridepublic void Showuser (list<user> users) {//TODO auto-generated method Stubmgridview.setadapter (new Useradapter (This,users));} @Overrideprotected Gridpresenter Createpresenter () {//TODO auto-generated method Stubreturn new Gridpresenter ();}}
public class Presenter2 {//viewiuserview Muserview;//modeliusermodel Musermodel = new USERMODELIMPL2 ();//? Pass through the constructor to Viewpublic Presenter2 (Iuserview muserview) {super (); this.muserview = Muserview;} Load data public void load () {//Load progress bar muserview.showloading ();//model for data acquisition if (Musermodel! = null) {Musermodel.loaduser ( New Userloadlistenner () {@Overridepublic void complete (list<user> users) {//data is loaded after the callback, Presented to view Muserview.showuser (users);}});}}
4) Memory leak issues in MVP
We found that the two acitivty we wrote earlier have common ground, that is, all new present, we extract the code to improve the reusability of the code.
There are many types of presenter in each Activitty, so in baseactivitty it is also necessary to extract the presenter into BASEPRESENTER,MVP, which is a reference to hold the view. So generics are used in Basepresenter
Public abstract class Basepresenter<t> {}
In Baseactivitty, the specific type of presenter is given to subclasses to determine, we only provide a method to generate presenter, where the generics are used many times, you need to pay attention to
Public abstract class Mvpbaseactivity<v,t extends Basepresenter<v>> extends actionbaractivity {protected T Mpresenter; @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate);//Create Presentermpresenter = Createpresenter ();//memory leak// Association Viewmpresenter.attachview ((V) this);} Protected abstract T createpresenter ();}
Memory leak Analysis: Join the model in the request Network load data, at this time assume that the activity because of insufficient memory, the GC is recycled, but the network load is not completed, then presenter still exists, and holds the activity reference, when the network loading data is completed, Presenter will use activity for data presentation, when activity has been recycled, there is a memory leak, will be error, so the solution is: When the view is recycled, presenter to release its association.
Since it is presenter to disassociate from view, the logic of association and release must be in the presenter, using a weak reference package view, on the grounds that the use of weak references, when the GC is scanned, is immediately recycled. Somake the following modifications to base presenter:
Public abstract class Basepresenter<t> {//When memory is low, free memory protected weakreference<t> mviewreference;
To create an association and disassociate method:
Logic to associate: Create a weak reference and wrap the view
Disassociate logic: Determine if weak references are not empty, empty weak references, and set to empty, completely free
To associate public void Attachview (T view) {mviewreference = new weakreference<t> (view);} Disassociate public void Detachview () {if (mviewreference! = null) {mviewreference.clear (); mviewreference = null;}}
Exposes a method for other classes to remove a view from a weak reference
Protected T GetView () {return mviewreference.get ();}
Gridpresenter InheritanceBasepresenter, implementation of Object abstraction method
public class Gridpresenter extends Basepresenter<iuserview>{//view//iuserview Muserview;//modeliusermodel Musermodel = new Usermodelimpl ();/*public gridpresenter (Iuserview muserview) {super (); this.muserview = MUserView;} *///load data public void load () {//Load progress bar//muserview.showloading (); GetView (). showloading ();//model Perform data acquisition if (Musermodel! = NULL) {Musermodel.loaduser (new Userloadlistenner () {@Overridepublic void complete (list<user> users) {// After the data is loaded, the callback is sent to the view to show//muserview.showuser (users); GetView (). Showuser (users);}});}}
The baseactivity is then modified:
Public abstract class Mvpbaseactivity<v,t extends Basepresenter<v>> extends actionbaractivity {protected T Mpresenter; @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate);//Create Presentermpresenter = Createpresenter ();//memory leak// Association Viewmpresenter.attachview ((V) this);} Protected abstract T createpresenter (); @Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); Mpresenter.detachview ();}}
OnCreate method in the association View,ondestroy method to clear the association, all the logic about the memory leak is complete, well, the analysis of the MVP model to this end, more applications to everyone in the project to use the model, and continue to summarize.
On the MVP model of wirelessly