问题
So I have an a presenter that is already tied to an activity. The book says that one presenter should be tied to one view. But now I am adding a few fragments and lots of custom views. I am considering a fragment to be a view as well. The custom views will contain a little bit of logic in them. Both the fragments and custom views are contained in my activity of course.
My question is, should I re-use the same presenter in the fragment and custom views or should each view get its own presenter? I realize this is all opinion based but I want the best approach for testing and keeping code clean.
If i do have one presenter for all these fews then then interface the presenter uses will have many callback methods in it. Meanwhile if i did the opposite and created one presenter for each view it might be easier to read but how would i test it ?
回答1:
View (Activity) can have multiple Presenters. In case of having multiple CustomViews for Activity, you can have one giant Presenter or Presenter per each CustomView. It depends on this:
If all
CustomViewsshare same needs, onePresenterfor allCustomViewsis enough. Still two options forPresenter'sscope:Presenterhas ActivityScope.ActivityusesPresenterand gets called fromPresenter. Then sends commands, data toCustomViewsPresenterhas ViewScope. EachCustomViewcreates and destroys samePresenter
In case of
CustomViewsnot sharing same needs, having onePresenterandViewInterface, they will contain methods of allCustomViewsneeds, so eachCustomViewhas to implement all declared methods inViewInterface, leave some empty.If
CustomViewshave different needs and method calls toPresenter, they should have their ownPresenter.- If
CustomViewshave different needs and also some common needs, they share common need in onePresenter, specific needs in their ownPresenters. Example for this:ActivityOnehasCustomViewOneandCustomViewTwo. CommonPresenterfor bothCustomViewscan beFeedPresenter(considering both CustomViews have Feed List). ThenCustomViewOnewill haveCustomPresenter1andCustomViewTwowill haveCustomPresenter2for their specific needs.
回答2:
Best practice is to create a basepresenter , then create presenter for each view implementing basepresenter
来源:https://stackoverflow.com/questions/43104614/android-mvp-can-i-have-multiple-presenters-for-custom-views-and-fragments