javaandroidmvparchitectural-patterns

Should I create Presenter and Model for each Activity or not?


I've read some articles about using MVP pattern in Android. The best way for me is to create contract(one interface for each Model,View and Presenter). The question is should I create such a contract for each Activity or how to implement it if I have couple of activities in my app. Thank you


Solution

  • In short,

    There is no limitation, it's completely up to you and depends on your project structure. So, you have to find the best one that suits your project.

    But, let me clear everything in broader sense

    First of all, you should understand that, these architectural patterns are developed to make life easier for developers, but they never bind any exact requirement on how many class you will create for which part. This completely depends on project structure and what are the functions of app. Everything is up to the developers - you can design in your own way. But, obviously, there is best practices that many developers follow.

    Model is responsible for data handling or data management. So, how many models will be there, that has no relationship with how many activities or views are there. So, number of model class is completely dependent on your data sets and how you are representing them for easier access.

    We can consider that each activity in your project represents each of the separate UI screens of your app. In that sense, for each activities you should create at least one view.

    So, that was the main theme of the MVP, i.e. Model and View will be isolated from each other. But, what about Presenter? Yes, it is the one which connects Model and View for communication in between them as they are not directly connected.

    Presenter actually contains the business logic for your app, so that one view can request something from presenter and presenter collect that from model and sends back to view. So, best practice is to create one presenter for each view for keeping everything simple. But, obviously there are scenarios, where same business logic can be used by several views. In that case one presenter can serve two separate views. That's completely fine also.

    So, now you should understand that creating interface for the view and presenter is not absolutely necessary. But in case, you are following one good practice of MVP that I have mentioned earlier to try to create one presentation for each view, in that case creating an interface for them will make sense as you will be able to know all the behaviors supported by view to be implemented by your presenter.