MVC pattern on Android

2018-12-31 23:29发布

Is it possible to implement the model–view–controller pattern in Java for Android?

Or is it already implemented through Activities? Or is there a better way to implement the MVC pattern for Android?

21条回答
爱死公子算了
2楼-- · 2019-01-01 00:02

The actions, views and activities on Android are the baked-in way of working with the Android UI and are an implementation of the model–view–viewmodel (MVVM) pattern, which is structurally similar (in the same family as) model–view–controller.

To the best of my knowledge, there is no way to break out of this model. It can probably be done, but you would likely lose all the benefit that the existing model has and have to rewrite your own UI layer to make it work.

查看更多
栀子花@的思念
3楼-- · 2019-01-01 00:04

There is not an implemented MVC architecture, but a set of libraries / examples exists to implement an MVP (model–view–presenter) architecture.

Please, check these links:

Google added an example of an Android architecture MVP:

查看更多
春风洒进眼中
4楼-- · 2019-01-01 00:05

It was surprising to see that none of the posts here answered the question. They are either too general, vague, incorrect or do not address the implementation in android.

In MVC, the View layer only knows how to show the user interface (UI). If any data is needed for this, it gets it from the Model layer. But the View does NOT directly ask the model to find the data, it does it through the Controller. So the Controller calls the Model to provide the required data for the View. Once the data is ready, the Controller informs the View that the data is ready to be acquired from the Model. Now the View can get the data from the Model.

This flow can be summarised as below:

enter image description here

It is worth noting that the View can know about the availability of the data in the Model either through Controller -- also known as Passive MVC -- or by observing the data in the Model by registering observables to it, which is Active MVC.

On the implementation part, one of the first things that comes to mind is that what android component should be used for the View? Activity  or Fragment ?

The answer is that it does not matter and both can be used. The View should be able to present the user interface (UI) on the device and respond to the user's interaction with the UI. Both Activity  and Fragment  provide the required methods for this.

In the example app used in this article I have used Activity for the View layer, but Fragment  can also be used.

The complete sample app can be found in the 'mvc' branch of my GitHub repo here.

I have also dealt with the pros and cons of MVC architecture in android through an example here.

For those interested, I have started a series of articles on android app architecture here in which I compare the different architectures, i.e. MVC, MVP, MVVM, for android app development through a complete working app.

查看更多
登录 后发表回答