How to use Java Observer (Observable, Object) update function?

I have a basic MVC template created in Java that uses the Observable / Observer class / interface.

Observable Observer Observable/Observer Model Controller View View triggers an event to the Controller, when the user interacts with the GUI. - Eg presses a button, fills in a field, etc. Model triggers an event to the View when it updates its state. - Eg when the a button was pressed and the Controller requests new results. 

My question is about the Observer function

 update(Observable obs, Object arg); 

This is one function, but I have many different types of updates that can be done in my View , for example. How can I elegantly distinguish between updating to, say, my search results or displaying additional information? These are two completely different updates that use different objects from the Model.

My first idea was to use Object to pass a string that describes which update is required.

 "UpdateResults" "DisplayAdditionalInformation" "AddQuestions" 

but it seems erroneous and ugly. My second instinct was to create an EventObject that would be passed as an object, but then I should keep asking what type of EventObject I am using:

 if (arg instanceof ResultEventObject) // Get results from model else if (arg instanceof InformationEventObject) // Get information from model else if (arg instanceof QuestionsEventObject) // get questions from model 

My third idea is to simply update everything, but it seems pointless to be ineffective.

I probably misunderstand the Observable / Observer interface, or I do not use update (), as the authors assumed. So my question is: how to use the update function correctly when I have many different types of updates or events to process?

+4
source share
2 answers

You can create your own Listener interfaces depending on what kind / model you are listening to. This allows your view / model to accurately convey the information your controller needs and makes it easier to control the unit test controller.

To listen to the model, updating the entire simplest solution, and you can do it if performance is not a problem.

+1
source

Yes, I think it's better to use the Listener interface

check this note http://www.softcoded.com/web_design/java_listeners.php

+1
source

Source: https://habr.com/ru/post/1416145/


All Articles