Android MVPR Architecture Mode-part1

Source: Internet
Author: User
<span id="Label3"></p>Android MVPR Architecture Mode-part1 <blockquote> <blockquote> <ul> <li>Original Link: mvpr:a flexible, testable ARCHITECTURE for ANDROID (PT. 1)</li> <li>Original Author: Matthew Dupree</li> <li>Development technology Front www.devtf.cn</li> <li>Translator: chaossss</li> <li>Reviewer: Mr.simple</li> <li>Status: Complete</li> </ul> <p>Comprehensive unit testing can improve the code quality of internal systems because each component of the system needs to be tested, so each unit needs to be built outside the system and tested in a test environment. Unit testing of an object requires creating the object, providing the dependency that the object requires, and interacting with it, ultimately verifying that the output of the test environment is consistent with what is Expected. therefore, in order for a class to be easy to unit test, the dependency of a class must be clear, and it can be easily substituted and explicitly invoked and Validated. In the field of software engineering, This means that code must be loosely coupled, cohesion, that is to say: design Excellent.</p> <p>Steve Freeman and Nat Pryce, or Test-driven object-oriented development.</p> </blockquote> </blockquote><p><p>One of the reasons I've been trying to get Google's IO App to be unit tested recently is to verify that Freeman and Pryce summarize unit tests in References. Even now I'm not refactoring any of the Activity in iosched, but I've felt what they say in refactoring the Code.</p></p><p><p>The activity I'm Refactoring now is sessiondetailactivity, and if you've been watching me, you'll know what activity I'm talking about, but if you're only looking at my post for the first time, you can look at the following diagram to see What is the interface of sessiondetailactivity?</p></p><p><p></p></p><p><p>As I said in the preface to this series of posts, there are a few problems that must be solved to make sessiondetailactivity available for unit testing. As I said in my previous article in this series, it is a challenge to unit-test its dynamically constructed View, but in that blog post, I mentioned that my solution to the problem is not a blog post, because there is a cyclic dependency between view and Presenter.</p></p><p><p>Cyclic dependencies are a symptom of big problems with Android application architectures: both Activity and Presenter violate the principle of single responsibility, and they need at least two things to do: bind the data to the View and respond to the User's Input. This is why the Sessiondetailactivity class is used as the Model for Android development, allowing the class to have more than 1000 lines of Code.</p></p><p><p>I believe there is a better way to structure our application, and in the next blog post, I will propose a new architecture with the following features:</p></p> <ol> <ol> <li><p>To break the multiple responsibilities that are normally the responsibility of Presenter and Activity</p></li> <li><p>Breaking the cyclical dependencies that exist between View or Activity and Presenter</p></li> <li><p>Allows us to construct a dependency injection of all objects that show data to the user and the corresponding user input</p></li> <li><p>It is easy for UI-related business logic to be unit tested, and it is not possible to be built to perform their duties without the necessary dependencies, and to modify the behavior of objects by leveraging aggregation and POLYMORPHISM.</p></li> </ol> </ol><p><p>In this blog post, i'll Try to summarize the reasons for developing a new Android application Architecture.</p></p>Why do I need a new architecture? Activity/fragment/presenter will become Bloated.<p><p>Activity and Fragment (hereafter I will collectively refer to activities, but what I say also applies to Fragment) is a typical violation of the principle of single responsibility:</p></p> <ul> <ul> <li><p>Handling of View Events</p></li> <li><p>Update Data Model</p></li> <li><p>Call Other View</p></li> <li><p>Interacting with system components</p></li> <li><p>Handling System Events</p></li> <li><p>Update View based on system events</p></li> </ul> </ul><p><p>As Richa says, Most of these duties are stripped from the activities, but even if we do, activities violates the principle of single Responsibility. Even the simplest activities need to bind the Model's data to the View and make the user input appropriate, for example:</p></p><pre class="prettyprint"><code class="language-java hljs "><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-class"><span class="hljs-class"> <span class="hljs-keyword">class</span> <span class="hljs-title">sessiondetailactivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">baseactivity</span> <span class="hljs-keyword"></span> implements <span class="hljs-title"> Loadermanager</span>. <span class="hljs-title">loadercallbacks</span><<span class="hljs-title">Cursor</span>, <span class="hljs-title">observablescrollview</span>. <span class="hljs-title">Callbacks</span> { </span></span> <span class="hljs-comment"><span class="hljs-comment">//...</span></span> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword">protected</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onCreate</span></span>(Bundle Savedinstancestate) {<span class="hljs-comment"><span class="hljs-comment">//responsibility 1:responding to User's action (in this case, a click)</span></span>Maddschedulebutton.setonclicklistener (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>View.onclicklistener () {<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">OnClick</span></span>(view View) {<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Starred =!mstarred; Sessionshelper helper =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Sessionshelper (sessiondetailactivity.<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); Showstarred (starred,<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>); helper.setsessionstarred (msessionuri, starred, mtitlestring);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(Build.VERSION.SDK_INT >= Build.version_codes. Jelly_bean) {maddschedulebutton.announceforaccessibility (starred? GetString (r.string.session_details_a11y_session_added): getString (r.string.session_details_a11 y_session_removed)); }<span class="hljs-comment">/ <span class="hljs-comment">* [analytics:event] * Trigger:add or remove a session from My Schedule. * CATEGORY: ' Session ' * ACTION: ' starred ' or ' unstarred ' * label:session title/su Btitle. * [/analytics]</span> */</span>Analyticsmanager.sendevent (<span class="hljs-string"><span class="hljs-string">"Session"</span></span>, starred?<span class="hljs-string"><span class="hljs-string">"starred"</span></span>:<span class="hljs-string"><span class="hljs-string">"unstarred"</span></span>, mtitlestring,<span class="hljs-number"><span class="hljs-number">0</span></span>L); } });<span class="hljs-comment"><span class="hljs-comment">//...</span></span> <span class="hljs-comment"><span class="hljs-comment">//responsibility 2:fetching and binding data</span> to the view</span>Loadermanager Manager = Getloadermanager (); Manager.initloader (sessionsquery._token,<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>,<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); Manager.initloader (speakersquery._token,<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>,<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); Manager.initloader (tag_metadata_token,<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>,<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); }</code></pre><p><p>The sessiondetailactivity in Google iosched apps is a great example of how Activity can become bloated even if it is only responsible for binding data to View and responding to user Input. Even if we peel this part of the code from sessiondetailactivity, there is a class with more than 700 lines of Code. Don't believe me? You can go to see the source code, Presenter also because the activity of the reason become bloated: Presenter is usually responsible for binding data and response to user input, so Presenter also need to be like Activity by stripping additional responsibilities to be thin.</p></p>Activities/fragment/presenter usually has a cyclic dependency between the View<p><p>Activities typically perform the duties of binding data to a view and responding to user input through the loop between them and the view (for example, View as a setcontentview () method parameter). Here's an example:</p></p><pre class="prettyprint"><code class="language-java hljs ">Maddschedulebutton.setonclicklistener (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>View.onclicklistener () {<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">OnClick</span></span>(view View) {<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Starred =!mstarred; Sessionshelper helper =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Sessionshelper (sessiondetailactivity.<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); Showstarred (starred,<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>); helper.setsessionstarred (msessionuri, starred, mtitlestring);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(Build.VERSION.SDK_INT >= Build.version_codes. Jelly_bean) {maddschedulebutton.announceforaccessibility (starred? GetString (r.string.session_details_a11y_session_added): getString (r.string.session_details_a11 y_session_removed)); }<span class="hljs-comment">/ <span class="hljs-comment">* [analytics:event] * Trigger:add or remove a session from My Schedule. * CATEGORY: ' Session ' * ACTION: ' starred ' or ' unstarred ' * label:session title/su Btitle. * [/analytics]</span> */</span>Analyticsmanager.sendevent (<span class="hljs-string"><span class="hljs-string">"Session"</span></span>, starred?<span class="hljs-string"><span class="hljs-string">"starred"</span></span>:<span class="hljs-string"><span class="hljs-string">"unstarred"</span></span>, mtitlestring,<span class="hljs-number"><span class="hljs-number">0</span></span>L); } });</code></pre><p><p>Sessiondetailactivity holds a reference to maddschedulebutton, and Maddschedulebutton also holds a reference to Sessiondetailactivity. I will say that such loops rely on limiting the way we are typically used to implement UI-related business logic in Activities.</p></p><p><p>MVP Presenter have the same cyclic dependencies as they are with View, and before I can explain in detail, I have to briefly describe the differences between view and MVP patterns in the traditional Android application Architecture.</p></p><p><p>The view in MVP mode is like I defined, just one of the three MVP models, usually defined as an interface, and typically implemented in view in Activity,fragment or Android legacy Architectures. The view in the Android legacy architecture is like its name, which is a subclass of VIEW.</p></p><p><p>Using the view and Presenter in MVP mode is simply recreating the same cyclic dependency between view and activities in the Android legacy architecture between Them.</p></p><p><p></p></p><p><p></p></p><p><p>Presenter needs the view in the MVP mode so that they can bind the data to the view in the VIEW,MVP mode in MVP mode, which requires a reference to the Presenter so that it can pass the click and other UI-related events to Presenter. Square's blog post has the implementation of the MVP model of cyclic DEPENDENCE.</p></p><p><p>Cyclic dependencies can cause problems when you want to build objects (or typically) for unit Tests. however, in general, We do not consider the issue of cyclic dependencies between the MVP mode view and Presenter or activities and view, because activities and Fragment are initialized by the system, and because we are not injecting them with dependency injection Activity and/or Fragment dependence. instead, we are simply initializing any dependencies that the Activity requires in the OnCreate () method:</p></p><pre class="prettyprint"><code class="language-java hljs "><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-class"><span class="hljs-class"> <span class="hljs-keyword">class</span> <span class="hljs-title">myactivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Activity</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Mvpview</span> { </span></span>View mbutton;<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword">protected</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onCreate</span></span>(Bundle Savedinstancestate) {<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>. onCreate (savedinstancestate); Setcontentview (r.layout.activity_browse_sessions);<span class="hljs-comment"><span class="hljs-comment">//...</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>Presenter Presenter =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Presenter (<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); Mbutton.setonclicklistener (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>View.onclicklistener () {<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">OnClick</span></span>(View V) {presenter.onbuttonclicked (); } }); }}</code></pre><p><p>Initializes a hybrid class that relies on the onCreate () method, however, restricts our use of composition and polymorphism to implement UI-related business Logic. Here's An example of how you should use polymorphism to implement UI-related business Logic: Suppose you develop a user-used app, and users have different privileges at different levels, then they need to verify or answer questions from other users to improve their ratings. We can imagine that there are many buttons to complete different functions depending on the level of completion, or the initial state of View determined by the user level. Polymorphism provides us with a neat, extensible way to implement this logic: we create a Presenter to bind different levels to the user, regardless of the level of the user, we can upload the View of the MVP pattern to a specific Presenter subclass, And let the subclass handle the corresponding Click event or render the UI based on the User's level. Of course, There are many ways of architecting Android apps that allow us to take advantage of polymorphism in the presence of View-cycle dependencies in Presenter and MVP models, but these methods are not elegant enough, or they make a great contribution to the completion of unit Testing.</p></p><p><p>The remainder of this blog post is not enough for me to describe the solutions I remember, but I can briefly say why it is not ideal to solve the cycle-dependent approach between View and Presenter in the MVP model. You can imagine that we could just create a View or Presenter of MVP mode without any reliance on their duties. In other words, we can look like this:</p></p><pre class="prettyprint"><code class="language-java hljs "><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-class"><span class="hljs-class"> <span class="hljs-keyword">class</span> <span class="hljs-title">myactivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Activity</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Mvpview</span> { </span></span>View mbutton;<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword">protected</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onCreate</span></span>(Bundle Savedinstancestate) {<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>. onCreate (savedinstancestate); Setcontentview (r.layout.activity_browse_sessions);<span class="hljs-comment"><span class="hljs-comment">//...</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>Presenter Presenter =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Presenter ();<span class="hljs-comment"><span class="hljs-comment">//****</span></span>Presenter.setview (<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>);<span class="hljs-comment"><span class="hljs-comment">//****</span></span>Mbutton.setonclicklistener (<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>View.onclicklistener () {<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">OnClick</span></span>(View V) {presenter.onbuttonclicked (); } }); }}</code></pre><p><p>This way we can solve the problems mentioned above through polymorphism, but this does not break the cyclic dependency. What it can do is allow us to create an object in an invalid State. This is not the most concise solution, put it in Freeman and Pryce words:</p></p> <blockquote> <blockquote> <p>"create or not create, no need to try"</p> <p>We want to make sure that a valid object is always created, partially creating an object and then completing it by setting its properties is fragile ...</p> </blockquote> </blockquote>Conclusion<p><p>Presenter and activities violate the principle of single responsibility, and they are often responsible for binding data to View and responding to user input, which can make activities and Presenter Bloated.</p></p><p><p>Presenter and activities often have multiple responsibilities because of their cyclical dependence on the view, and even if such circular references do not cause problems, it will be more difficult to unit test the view and/or Presenter, and limit our use of polymorphism to implement the UI phase The business logic of the SHUTDOWN.</p></p><p><p>As I said before, I think there will be a way to apply the architecture without the above martyrs, and in the next blog post, I will present an alternative architecture.</p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android MVPR Architecture Mode-part1</p></p></span>

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.