Analysis of Android source code design patterns and practices (26)
Chapter 2 MVP application architecture model 1. Introduction to MVP
The MVP mode is an evolutionary version of the MVC mode. The full name of the MVP is Model-View-Presenter. Currently, MVP is becoming more and more important in Android application development.
In Android, business logic and data access are tightly coupled. Many inexperienced developers may insert various business logic into an Activity, Fragment, or custom View, this will make the individual types of these components bloated. If you do not extract the specific business logic, when the UI changes, you need to extract the specific business logic from the original View, which will inevitably be troublesome and error-prone.
2. Benefits of using MVP
(1) The MVP mode removes the coupling between views and models, effectively reducing the View complexity. At the same time, it brings about good scalability and testability to ensure system integrity and flexibility.
(2) MVP mode can separate the display layer from the logic layer, and communicate with each other through interfaces to reduce coupling. The idealized MVP mode can achieve the same logic code with different display interfaces, because they do not depend on specifics, but on abstraction. This allows the Presenter to be applied to any UI that implements the View logic interface, so that it has wider applicability and ensures flexibility.
3. Three MVP roles
(1)Presenter-Interactive intermediary:PresenterMainly for communicationViewAndModelFromModelAfter retrieving data at the layerViewLayer to makeViewAndModelThere is no coupling between them, and the business logic is also fromViewRole.
(2)View-User interface:ViewUsually refersActivity,FragmentOrViewControl, which containsPresenterMember variable. UsuallyViewYou need to implement a logical interfaceViewToPresenterAnd finally,PresenterCallViewThe logical interface returns the resultViewElement.
(3)Model-Data Access:ModelThe role mainly provides the data access function.PresenterData needs to be stored and retrieved at the Model layer,ModelIt is like a data warehouse. To put it bluntly,ModelIt is a set of roles that encapsulate the database DAO or the network to obtain data, or two data methods.
4. Differences with MVC and MVVM 1. Differences with MVC
It can be seen that the coupling of MVC is still high, and View can directly access the Model, resulting in a loop between the three. The main difference between the two is that the View in the MVP cannot directly access the Model, and a request must be sent through the Presenter. The View and Model cannot communicate directly.
2. Differences from MVVM (Model-View-ViewModel)
MVVM is very similar to MVP. The only difference is that the View and Model are bound in two directions. If one of the two changes, the two changes will be reflected on the other. The MVVM mode is somewhat like the relationship between ListView, Adapter, and Dataset. When the dataset changes, the View is directly updated after the notifyDataSetChanged of the Adapter is called, and there is no coupling between them, makes ListView more flexible.
5. Simple MVP implementation
Refer:
1. androidmvp
2. archi
6. lifecycle of MVP, Activity, and Fragment
BecausePresenterRegular holdActivityIfActivityDestroyedPresenterAlways holdActivityObject To makeActivityThe object cannot be recycled, and memory leakage occurs.
The solution is to use weak references, Activity, and Fragment lifecycles to solve this problem. First, createPresenterAbstract:
Public abstract class BasePresenter
{Protected Reference
MViewRef; // weak reference of the View Interface Type public void attachView (T view) {mViewRef = new WeakReference
(View); // establish Association} protected T getView () {return mViewRef. get (); // obtain View} public boolean isViewAttached () {return mViewRef! = Null & mViewRef. get ()! = Null; // determine whether to establish an association with the View} public void detachView () {if (mViewRef! = Null) {mViewRef. clear (); // unassociate mViewRef = null ;}}}
NormallyViewThe type should beActivityOrFragment.
CreateMVPBaseActivityThis base class declares periodic functions to controlPresenter. The Code is as follows:
Public abstract class MVPBaseActivity
> Extends Activity {protected T mPresenter; // Presenter object @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); mPresenter = createPresenter (); mPresenter. attachView (V) this) ;}@ Override protected void onDestroy () {super. onDestroy (); mPresenter. detachView ();} protected abstract T createPresenter ();}
MVPBaseActivity contains two generic types: View Interface Type and Presenter type.
7. Reference
PS: Now the Reading Notes series of "Analysis and Practice of Android source code design patterns" are over. This book has been around for nearly two months, and the gains are really huge, in the future, I will take the time to read it again several times to learn about it! During the course of writing this reading note, I am very grateful for your support. The comments are all encouraging and give me a lot of confidence. I was most excited by one of the authors of this book.He honghuiI also gave me encouragement, and I would like to thank you again here.
A while ago, I saw many bloggers write annual summaries. After reading these summaries, I also felt very touched. Now I have been developing Android for a year and a half. Although it is not a good player. However, work problems can be solved independently (after all, Google ~, After all, I am the only one. At the same time, I have a positive attitude towards my work and study.
Talking about the original intention of writing a blog: When I wrote a blog for almost one year, it was also a coincidence that I wrote a blog because I often read some open source projects before writing a blog, for example, in the android-open-project on Github, every time I search for android-open-project on Github (I don't even bother to save bookmarks !), There are many similar ones... Finally, one day I felt really troublesome (how slow you are), so I wrote my first blog on these URLs that I often used: Android open source and dry goods website summary, save a bookmarks. After tasting this convenient benefit, we officially started the CSDN blog tour.
A few days ago, I happened to see a great god's blog. I read this great god's blog that has been written for nearly 10 years, and there are high-quality articles every month. The knowledge involved is also in all aspects. It shocked me, so I learned from the role model and continued to work hard this year. Now that I have started, I will stick to it.