directory

MVP stuff (1)… Speak with the scene

MVP stuff (2)… A Preliminary study on MVC Architecture

MVP stuff (3)… Using MVC in Android (Part 1)

MVP stuff (4)… Using MVC in Android (Part 2)

MVP stuff (5)… The relationship between the mediator model and MVP

MVP stuff (6)… MVC turned into MVP

MVP stuff (7)… Repository Design analysis

Why MVC first?

If you want to better understand MVP, and in the actual development of flexible application, then it is necessary to understand its low version of MVC, they are just one step away, first understand MVC and then learn MVP, MVP advantages can be highlighted, so that the continuous learning will deepen the understanding of MVP.

(2) A look at the MVC architecture:

What does MVC do? Is it a design pattern? Is it a frame? Is it architecture? The definitions and responsibilities of the MVC layers

From the last chapter, you have a general understanding of MVC. Before starting this chapter, I hope you can read the previous chapter first, otherwise you may get “blackout”. In the previous article, we covered the basic responsibilities of the three layers of MVC in detail. Let’s review the three “pieces” :

Model layer

1. Javabeans are not models, but models can contain javabeans’ responsibilities, but they do not have to. Model is used to process data, such as fetching data (local or server-side), and data processing, such as CURD.

The View layer

1. Its main responsibility is to present the data of the Model and actively inquire about the status or passively monitor it. 2

Controller

1. Receive the View operation, transfer it to Model 2, and change the state of the View

At the same time, two problems remain:

1. How to put these three pieces together? How do I write it in Android? . 2, the view in the execution tasksRepository getTaskCache (), is how to know tasksRepository data is ready? How do YOU tell the view?

Put the pieces together

In pattern design, we use a diagram to reflect the relationship between objects, as shown below:

Believe everyone understand MVC to students to familiar with the drawing, OK, but now this picture we don’t put down the table first, because of considering our introduction is an abstract architecture, combined with the abstract architecture diagram, even can’t cut into the well, so I want the realization process, when you have a clear understanding, Go back and re-understand the picture. I originally wanted to put this picture in the second half of the article, but on second thought, it is a little inappropriate, because we have already passed a whole article to explore MVC in the last period, and it is time to post the MVC architecture picture to meet the occasion…

So how does MVC relate to each other?

We still describe the relationship between MVC and MVC through the real scene, so that we can have an initial intuitive understanding of the relationship between the three, and play an effect of throwing a brick to attract others. There is no more nonsense, and the scene begins.

scenario

In today’s society, real estate agents are an essential link for us to rent a house. I believe most of us have dealt with real estate agents. Well, let’s restore the process of renting a house.

First, identify the characters

There are three characters in this scenario, the tenant, the agent, and the landlord,

Second, choose the Angle

Let’s describe the rental scenario from the tenant’s point of view, considering only the forward process.

Third, scene description

After receiving the demand, the agent finds a suitable landlord through screening, so the agent starts to contact the landlord and inquire about some matters related to the house rent. If the agent thinks it is suitable, he will inform the client of the feedback. If the client thinks it is suitable, Mediation will be the tenant and the landlord about further negotiation in the store, and, if you can help make contract, so this far, and intermediary finished at this stage of the work, the rest of the things, such as the tenants pay the rent to the landlord every quarter, or ask the landlord to the use of home appliances, or the landlord asked if the tenant lease expired relet, etc., All these communications can be completed without intermediaries, that is to say, intermediaries are not necessarily needed as a bridge of communication between them, but it does not mean that intermediaries are not available in future scenarios. For example, in the process of renting a house, there are some differences between the tenant and the landlord, and they can also coordinate and communicate through intermediaries.

There is another form of intermediary, the tenant and the landlord can not see each other, the whole process is responsible for by the intermediary, this kind of house is called trusteeship, the tenant does not know who the landlord is, the landlord does not know who the tenant is, the contract is signed with the intermediary, we do not discuss this situation now.

Let me draw a picture of the appeal

The purpose of this picture is to retell the above scene description, and to give you an intuitive view of the interaction between the three.

Agent, tenant, landlord, and relate them to the three roles of MVC

Through the description of the appeal scenario and the responsibilities of the MVC objects in the previous post, it is clear who they really are, so let’s try to relate these objects

First, let’s look at the agent. He is responsible for implementing the tenants’ requirements and informing the landlord of these requirements. That is to say, he acts as the agent and communicates the tenants’ needs to the landlord.

When we look at the tenant again, he is the originator of demand, and he puts forward demand more actively than other objects. Just like View, it always puts forward demand to Controller, and it also takes the initiative to inquire the status of Model. Just like tenants, when they encounter problems, they will either seek an intermediary or consult the landlord. It is more appropriate to regard the tenant as View here.

Finally, the only role left is the landlord, and the last Model will be assigned to the landlord.

Next, we use MVC to sort out the relationship between intermediary, tenant and landlord

1, View To Controller

The above five picture, is the relationship between the MVC three objects, and the example of a business process, made a “convergence”, is an abstract to the concrete “convergence”, these lines with arrows in the architecture diagram, is used to explain the relationship between objects, is those who rely on the explanation, I added some events in the history of online again at the same time, In practice, such integration is not in line with common sense. For example, you cannot use a single business scenario To define the dependency relationship between objects, such as View To Controller. Is it only possible To use the scenario of renting a house? Obviously not, including the title after parentheses in each role. Therefore, in order to solve the problem of universality, people abstract such representational problem into a dependency relationship.

Architecture is blueprint, abstract existence, and framework is concrete, it is designed to solve a specific kind of problem.

Where does the MVC architecture diagram come from? Get rid of the concrete and look at the essence

In some cases, we need to introduce our software architecture, which requires us to have the ability to describe the architecture. I think it is a good idea to describe the concrete problem first, then describe the steps of pulling up, and finally state the abstract product, which is our architecture.

Put it into practice

I believe that you have a preliminary understanding of THE MVC architecture through the above large length, so let’s start the real use, remember that we used a requirement in the last article:

Requirements: lists load data and display

We are still using this requirement, because we have defined three layers of classes, and now we need to assemble them according to the MVC architecture:

Use in Android

To get started in the actual development phase, let’s create an Activity

public class MainActivity extends AppCompatActivity { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}Copy the code

Next, we add the three MVC objects defined in the previous article

Model :TasksRepository

Public class TasksRepository {// getTaskCache() {// getTaskCache() {// getTaskCache() {} // Get Data from disk cache Data getTaskDiskCache(){} // save a Data Boolean saveTask(Task Task){} // Sort Data Data orderData(Data Data, int orderType){} }Copy the code

View :TasksView

Public class TaskView {// When the list is initialized, Void viewCreate() {} void upDateList() {} // Just for UI void beginLoadData(){}}Copy the code

Controller :TasksController

Public class TasksController {void loadNomData() {}}Copy the code

Now we have Activity, TasksRepository, TasksView, TasksController

Now that we have these objects, we can combine them. Where do we start? Maybe we can take a hint from the MVC architecture diagram. Although the architecture diagram is simple, it has arrows and directions. In UML, these lines and arrows record the relationship between objects:

public class MainActivity extends AppCompatActivity { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TasksController controller = new TasksController(); TasksView view = new TasksView(); TasksRepository model = new TasksRepository(); Controller.setview (view); view.setController(controller); view.setModel(model); model.setController(controller); Model.setview (view) // Execute business controller.loadnomData (); }}Copy the code

I admit, I’m starting to throw a little bit of a spout again, but the way you write it, an Activity is a container like MVC, and it contains three MVC objects, is that a problem? Before continuing, to quote a concept, Is a… and Has a

Is a and Has a

Translated, that is, what am I, and what do I have

What am I?

// What animal am I? Class Animal implments Cat {// Void miaomiao(); }Copy the code

What have I got?

// What animals do I have? I have a Cat, a dog, a leopard class Animal{public Animal(Cat Cat) { This. Baozi = new baozi (); } void setDog(Dog Dog) {this.dag = Dog; }}Copy the code

MainActivity is an Activity. It has three objects: TasksRepository, TasksView, TasksController. The emphasis is on Has A, such dependency coupling degree is very high, there is basically no room for expansion, in order to reduce the coupling, can we make MainActivity fewer Has A? B: Sure.

I’m a cat. I have a dog and a leopard

// What animal am I? Class Animal implments Cat {// Void miaomiao(); Public Animal() {this.baozi = new baozi (); } void setDog(Dog Dog) {this.dag = Dog; }}Copy the code

TasksRepository (MVC), TasksView (MVC), TasksControlle (MVC), TasksRepository (MVC) At present, the mainstream is to choose View and Controller. Everyone chooses from the perspective of business. The first choice is View, because the Activity contains layout objects, so “close” turns the Activity into a View. I choose Controller because the life cycle of the Activity itself can be used to control the business process, which is more beneficial to Controller. To be honest, I haven’t explored which one is better, because I think both of these two schemes have their own focus, and I still need to consider the problem from the perspective of actual business. What if we suddenly wanted our Activity to be both a View and a Controller? Doesn’t that solve the problem of who we become? Personally feel or don’t of good, you can’t introduce oneself of time say: everybody good, I am a cat, also be a dog, I am male also be a woman, I believe the scene must be very chaotic at that time, we still keep the responsibility of class single. But maybe I can play with it as a Model someday, so FOR now I’m going to start with View, and then we’ll talk about Controller in the next chapter.

To update the UML

public class MainActivity extends AppCompatActivity implments TasksView{ @Override public void onCreate(@Nullable Bundle  savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); / / a little... }}Copy the code

Now that we’ve identified the Activity, we’re taking the first step. Next we’ll look at the initialization of the Controller, and in between we need to reference the concept of dependency injection.

Dependency injection

What is dependency injection? To first explain what a dependency is, look at the following code:

Class Animal{public Animal(Cat Cat) {this. Cat = Cat; This. Baozi = new baozi (); } void setDog(Dog Dog) {this.dag = Dog; } void miaomiao() {cat.miaomiao(); } void aoao() {baozi.called(); }}Copy the code

Aoao (aoao), aoao (aoao), aoao (Aoao), aoao (AoAO), aoao (AoAO), Aoao (AoAO), Aoao (AoAO), Aoao (AoAO), AoAO (AoAO), AoAO (AoAO), AoAO (AoAO) It’s new in the Animal constructor. Baozi and Cat are also Animal’s dependencies, but they are obtained in different ways. The way to obtain cat is by injection, and it is a dependency. So we call it dependency injection, and the form of dependency injection can be passed in through normal methods in addition to constructor parameters, such as the setDog method above, where we inject a Dog.

Benefits of dependency injection

For example, Cat in the above code can be an interface. Before we use Animal class, we can determine the implementation class of Cat. According to business requirements, the received Cat may be male, female, or beautiful short. If we initialize the Cat dependency in Animal, we may need to change the Animal class frequently depending on the business. Second, when the structure of Cat changes, Animal also needs to change Cat. If Cat needs other dependence, for example, Cat needs Cat food to survive, Animal also needs to rely on Cat food indirectly, and the coupling between objects is exposed. Therefore, Animal does not need to care about the dependence of dependence introduced from outside.

Dependency injection seems to be a very good design approach, so back to the problem of Contorller initialization, we know that the Controller is dependent on the View, so we need to inject the View into the Controller.

public class MainActivity extends AppCompatActivity implments TasksView{ @Override public void onCreate(@Nullable Bundle  savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TasksController = new TasksController(tasksView:this); }}Copy the code

Through dependency injection, we tie the fates of Controller and View together. View -> Controller -> View, Controller -> View, Controller -> View, Controller -> View, Controller -> View, Controller -> View The Controller is also initialized in the Activity via a new method, which makes it naturally dependent on the View. However, it is not injected into the View (MainActivity). Is there any way to do this? Of course there is, but the third way of dependency injection is to build a factory for the Controller that produces instances of the Controller, which I won’t go into here, but we’ll talk about in detail when WE talk about the Dagger.

Initialization of Model

So where does initialization of the Model(TasksRepository) go? And how does it relate to Controller and View? The answer can be obtained from the MVC architecture diagram and UML diagram of the framework. There is a one-way dependence between Controller and Model, namely Controller -> Model, and a two-way dependence between Model and View.

1, Controller -> Model 2, Model -> View 3, View -> Model

We only need to satisfy these three conditions. Let’s go ahead and look at the code like this:

public class MainActivity extends AppCompatActivity implments TasksView{ @Override public void onCreate(@Nullable Bundle  savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TasksController = new TasksController(tasksView:this); Model -> View and View -> Model TasksRepository Model = new TasksRepository(tasksView:this); //Controller -> Model model.setController(controller); }}Copy the code

First, initialize Model in Activty and inject View into Model. In this way, both Model -> View and View -> Model are satisfied. Second, The Controller created above is injected into the model using the setController method of the model, which satisfies the condition Controller -> View.

Stage summary

Now that we’re done assembling MVC pieces, let’s go through the process from the beginning

Implementation steps:

1, Is View, Activity implement View

Give the Activity the responsibility of the View.Copy the code

2. Controller -> View, create an instance of Controller in the Activity.

Tell the Controller to take care of something and receive the View's actions and transfer them to the ModelCopy the code

3, View -> Controller, inject View into Controller.

Receive the Controller and edit your state independent of the ModelCopy the code

4, Model -> View, create an instance of Model in the Activity.

Actively inquire about Model's status and present Model's dataCopy the code

5, View -> Model, inject View into Model.

Listen for changes to the Model and notify View of any changesCopy the code

Controller -> Model, inject Contoller into View

Listen for changes to the Model and notify the Controller of any changesCopy the code

Design ideas

Through the MVC architecture diagram, we tried to design UML, and determined the View’s ownership through the principle of Is A, Has A. Secondly, determined the dependency creation method through the principle of dependency injection. Thirdly, Controller, View were established through the MVC architecture diagram and UML. The relationship between Model and dependency injection principle completes the design of the whole framework.

conclusion

In the previous introduction to the responsibilities of MVC layers, the word “listen” appeared frequently. In the design of object-oriented languages, “listen” is an action, and its counterpart is the action of “get”. The current framework design is not perfect, there is no “listening” capability, there is imperfect code at all levels, and there is no practical content like inversion of control… I wanted to write it in one chapter, but it was too long, so I had to break it up. Always felt very quickly look at other people’s posts, that soon finished, but the real to code is really slow, mainly is worried that description is not clear, fear can’t express their ideas very clearly, and worry too clear expression of the will not appear again in repetitive, deleted, changed delete, all in all, I will try my best to finish this series, If you like it, give me a thumbs-up.

Original is not easy, I hope you pay attention to, collect, praise, let more students see, learn.

And finally, I want you to think about a question. Look at the following three pictures:

Question 1, the difference between Figure 1 and Figure 2, and whether Figure 2 counts as MVC

Question 2. Can MVC be designed like figure 3?

You are welcome to discuss and express your opinions in the comments section.

2020.01.06

Why does MVC feel so un” rigorous “?

In my opinion, the emergence of MVC is a milestone in software architecture design, because before this no one to consider framework of hierarchical meaning, but not used much of the so-called rules, simply let us know, in practice, however, how to find the MVC these three roles, 2 it is, who can understand MVC is there must be a lot of accumulation and experience. In my project is useful to the MVC design, once a problem bothering me, suppose we C, logic control it, the more the more thick, relative to the MV will become thinner, on the contrary, the less logic control in C, it is thin, and the thicker the MV, a reciprocal relationship, and C as excessive layer thick is I have been concerned about the question is: What principles are used to determine its thickness? I found that the thickness of C realized by people with the same experience is roughly the same, and the personnel allocation and ability are different in a project, so the thickness of C is different in the hands of each person. Why does this happen? Since everyone’s cognition is different, it is very difficult to unify people’s cognition, so we urgently need a standard, and the formulation of this standard may challenge some people’s cognition, which is a difficult and tiring process. It’s too broad for beginners to feel unprincipled and unsure if they’re using it correctly. When MVC reached a certain stage of development, people felt that it could not meet the needs of the present, so they added a single rule to it, which was also a rule across the ages, that M and V could not meet, and this single rule made MVC become the historical version, it became the MVP! Don’t look down upon this only a rule, a rule, means that the validation criteria, is this a rule let MVP than MVC is more easy to let people understand and use, were also more likely to let people go to verify, at least at the time of use will have a goal, that is whatever the reason, can’t let M and V meet, as long as you grasp the rule, Well, congratulations, at least someone will say, “Sorry, your MVP framework sucks, but at least it’s an MVP,” and the people who are reviewing your design will use it, and it creates a consensus, and consensus is good for the SPREAD and learning of MVPS, which is why there are so many individual MVPS on Github, MVC libraries are mostly developed by large organizations or companies, not for historical reasons, but because they are too broad to be controlled.