preface

  • inAndroidIn development, when you’ve combed through the requirements, you don’t need to write your first line of code immediately, you need to write it firstDesign the technical framework of the whole project
  • Today, I will give a comprehensive introductionAndroidThe prevailing technical framework in developmentMVC,MVPMVVMModel, and examples to explainMVPMode, I hope you like it.

directory


1. Why design the technical framework

  • Modularity makes the program modularized, i.e. high internal aggregation, low coupling between modules
  • Developers only need to focus on one point (view presentation, business logic/data processing)
  • Improve test efficiency to facilitate subsequent testing & problem location

Remember: Don’t design for design’s sake, or you’ll increase development


2. Mainstream technical framework for Android development

  • There are mainlyMVC,MVP,MVVMThree kinds of patterns
  • Below, I will introduce the above three modes in detail

2.1 the MVC pattern

  • The role that

  • Model specification

  • Problems with this model:Activities are unaccountable and bloated

    ActivityAs its life cycle functions, in addition to servingViewSome of the layer’s responsibilities (loading the layout of the application, accepting user actions) are also assumedControllerLayer responsibilities (processing of business logic)

    As interfaces grow & logic complexity increases,ActivityThe code volume of the class keeps increasing and getting fatter

2.2 the MVP pattern

  • In order to solve the problem of MVC mode, the responsibilities of View layer and Controller layer in the Activity are separated, so as to optimize and slim down the amount of Activity code, so MVP mode appears

  • The role that

  • Model specification

  • Advantages :(vs. MVC pattern)
  1. Less coupling: throughPresenterRealize data and View interaction, completely isolated View layer and Mode layer, the two do not interfere with each other

It avoids the direct contact between View and Model, and implements the communication between them through Presenter

  1. ActivityCode gets cleaner: simplifiedActivityOnly responsible for UI-related operations, the rest of the complex logic code is extractedPresenterLayer for processing

2.3 MVVM

In order to separate the M and V layers more and release the pressure of the Activity more, the MVVM pattern emerged

  • define

    VMLayer:ViewModelThe View data model and Presenter are combined

Basically identical to the MVP mode, rename the logical processing layer Presenter to ViewModel

  • Model specification

  • advantages

    Make the view layer(View)& control layer(the Controller)The degree of coupling is further reduced, and the separation of concerns is more complete and mitigatedActivityThe pressure of the

This article focuses on the MVC and MVP patterns, but focuses on the MVVM pattern.


3. The difference between MVC and MVP modes


4. The original intention of the emergence of the three modes

  • MVCEmergence of patterns

    To solve the problemProgram modularizationTherefore, MVC pattern appears: business logic, data processing and interface display are separated to organize the code, that is, divided into M, V, C layer;
  • MVPEmergence of patterns

    But the M and V layers still cross each other.Inadequate isolation, while writing to the Activity to make the Activity codebloated, thus, MVP emerges: it isolates the direct connection between M and V in MVC, further isolates M and V layers, and releases the pressure on activities.
  • MVVMEmergence of patterns

    In order toMore separation of M and V layers, to further release the pressure on the Activity, hence the emergence of MVVM: the coupling degree between V and M layer is further reduced, the separation is more complete, and the pressure on the Activity is further reduced.

Below, I’ll break down the core idea & usage of the most commonly used MVP model


5. MVP mode details

The core ideas of THE MVP model are analyzed in detail and illustrated with examples.

5.1 Core Ideas

Remove all the logic from an Activity into the View and Presenter interfaces & be done by concrete implementation classes. Specific implementation ideas are as follows:

  1. theActivityIn theUILogically abstracted asViewInterfaces & are done by concrete implementation classes
  2. Abstract the business logic intoPresenterInterfaces & are done by concrete implementation classes
  3. ModelThe class is the sameMVCPatterns ofModellayer

5.2 Implementation Procedure

A UML diagram of the MVP pattern

As you can see from the UML diagram, the steps for using the MVP pattern are as follows:

5.3 Example Description

This section explains the MVP mode through an English dictionary APP example

Introduction: The list structure of the project

The project structure of MVP technical architecture is very clear: the M, V, and P layers are divided into three folders: Model, View, and Presenter. Under each file are the corresponding interfaces and implementation classes

The Fanyi class of the Model layer is a JavaBean that implements parsing JSON information with GSON

Step 1: Set up the View layer (IView interface & Implementation class)

Public interface IfanyiView {void init(); public interface IfanyiView {void init(); // Initialize void SetInfo(String STR); Void SetError(); } /** * View implementation class: MainActivity class * Note: Public class MainActivity extends AppActivity implements IfanyiView {public class MainActivity extends appActivity implements IfanyiView { private EditText et; private TextView tv; CidianPresenter cidianPresenter; Override protected void onCreate(Bundle savedInstanceState) {super.oncreate (savedInstanceState); setContentView(R.layout.activity_main); // instantiate the object corresponding to P and findView init(); // Accept user input findViewById(r.i.btnfanyi).setonClickListener (new view.onClickListener () {@override public void OnClick (View v) {/ / the View layer data into the Presenter layer, note also pass MainActivity cidianPresenter. InputToModel (et. The getText (), toString (), MainActivity.this); }}); } @override public void init(){// Instantiate the object of class P and findView cidianPresenter = new cidianPresenter (this); et = (EditText) findViewById(R.id.editText); tv = (TextView) findViewById(R.id.tv); } @override public void SetError() {tv.settext (" query failed, please check network "); @override public void SetInfo(String STR){tv.settext (STR); } // MainActivity does FindView, setListener, cidianPresenter, etc.Copy the code

Step 2: Set up the Presenter layer (create the IPresenter interface & implementation class)

/** * Presenter: Public interface ICidianPresenter {void InputToModel(String input,Context) context); } /** * CidianPresenter class * */ public class CidianPresenter implements CidianPresenter onfanyiListener,ICidianPresenter { // 1. Declare the View layer corresponding interface, Model layer corresponding class IfanyiView fyV; fanyimodel fanyimodel; Public CidianPresenter(IfanyiView fyV){this.fyv = fyV; fanyimodel = new fanyimodel(); } // 3. Pass the data from the View layer to the Model layer. @override public void InputToModel(String input, Context Context){fanyiModel.handleData (input, Context, this); @override public void onSuccess(String STR) {fyv.setinfo (STR); @override public void onError() {fyv.seterror (); }} // note: // a. Keep a reference to IfanyiView to perform UI operations on the CidianPresenter class. Keeping the reference to the Model layer allows you to pass data from the View layer to the Model layerCopy the code

Step 3: Model Layer (Model layer interface & Implementation classes)

/** * Model layer interface: Ifanyi * Define the method used in the implementation class */ public interface Ifanyi {void HandleData(String Input,Context Context,final onfanyiListener  listener); String fanyiToString(fanyi fy); } /** * fanyiModel class */ public class fanyiModel implements Ifanyi {private fanyi fy = new Fanyi (); Public void HandleData(String Input,Context Context,final onfanyiListener Listener){// Use the Volley framework to asynchronously obtain translation data from the Youdao API on the network RequestQueue mQueue = Volley.newRequestQueue(context); StringRequest stringRequest = new StringRequest (" http://fanyi.youdao.com/openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q= "+input, New Response.listener <String>() {@override public void onResponse(String s) {Gson Gson = new Gson(); fy = gson.fromJson(s.trim(),fy.getClass()); // The callback listener returns the result of processing the data (translated result) to the Presenter listener.onsuccess (fanyiToString(fy)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { listener.onError();  }}); mQueue.add(stringRequest); } public String fanyiToString(fanyi fy){// handle parsed json data, convert it to UI output String strexplain = "解释 : "; String strphonetic = "pronunciation: "; String strweb = ""; If (fy.basic == null){return "what you are looking for is not translated correctly "; } for (int i = 0; i<fy.basic.explains.length; i++){ strexplain +=fy.basic.explains[i]+"\n"; if (i ! = fy.basic.explains.length-1 ) {strexplain +="\t\t\t\t"; } } strphonetic += fy.basic.phonetic +"\n"; for (int i = 0; i<fy.web.size(); i++){ for(int j = 0; j<fy.web.get(i).value.length; j++) { strweb += fy.web.get(i).value[j]+","; } strweb += fy.web.get(i).key+"\n"; strweb += "\t\t\t\t\t\t\t"; } return strexplain+"\n"+strphonetic+"\n"+strweb; }}Copy the code

At this point, on the MVP mode of the example explained, explained the end.


6. Summary

  • This article mainly explainsAndroidThe prevailing technical framework in developmentMVC,MVPMVVMmodel
  • So I’m going to continue with thisAndroidIn the knowledge of in-depth explanation, interested can continue to pay attention toCarson_Ho android Development Notes

Please give the top/comment a thumbs up! Because your encouragement is the biggest power that I write!