简体   繁体   中英

MVP: Presenter Singleton

I use history management in my ajax-web-application(GWT). When the user presses the backward or forward button, another view will be displayed. Every view will be only created once. My quesion is how can i handle the presenter.

I think there are two ways:
1. The view saves all data and after every history change event, a new presenter will be created. When the model needs some data, the presenter will ask the view for data and send them to the model.

2. The presenter saves all data and after every history change event, the presenter will be reused for the view. Thus the view has only the ui widgets and all changes made by the user will be redirected to the presenter.

I prefer the second way, but i am not sure if that is compatible to mvp. What do you recommend me?

There is a third way, and that is neither the presenter and the view save the data. The view contains only the ui widgets and is a singleton that is reused. The presenter contains the logic and local state and the presenter is created every time when called. By creating it everytime it's called it is assured the local state is fresh.

The outside data needed by the presenter can be or queried from the server as part of the startup of the presenter, but that might not work if you need to pass data between presenters. Therefor store the data in a global object maintained by the application and when the presenter is called the specific object needed is passed to the presenter via the constructor of the presenter. By removing the data out of the presenter and view you keep it more simpler as the presenter/view doesn't have to manage. This code will also get data from the server if not present. It makes it also more robust for when the user goes to a page by say editing the url which will load a specific presenter/view. By moving the data management out of the presenter/view you don't have to worry about wrong data in the presenter/view as the application will handle what presenter/view the user will actually get, which might be a different page than requested because the page requested is invalid for the data present.

It would matter less if you ensure the presenter is lightweight ie has more or less no state ( my interpretation ).

I would prefer delegating away the code the data state load/save to another class invoked from presenter and make presenter a singleton.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM