How to Use Java Observer's update(Observable,

2019-06-24 01:01发布

I have a basic MVC pattern 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.
- E.g presses a button, fills in a field, etc.

Model triggers an event to the View when it updates its state.
- E.g 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 kinds of updating to do in my View for example. How do I elegantly distinguish between an update to, say, my search results or the displaying of additional information? These are two completely different updates that use different objects from the Model.

My first idea was to use the Object to pass a string which would describe what update is required.

"UpdateResults" "DisplayAdditionalInformation" "AddQuestions"

but that seems error-prone and ugly. My second instinct was to create an EventObject that would be passed as an Object, but then I have to keep asking what kind of EventObject I'm 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 that seems pointlessly inefficient.

I am probably not understanding the Observable/Observer interface correctly or I'm not using update() as it was intended by it's authors. Therefore my question, how do I use the updatefunction properly when I have many different types of updates or events to process?

2条回答
我想做一个坏孩纸
2楼-- · 2019-06-24 01:32

You can create your own Listener interfaces depending on what view/model you are listening to. This allows your view/model to pass exactly the information required to your controller and will make it easier to unit test the controller.

For listening to the model, updating everything is the simplest solution and you can do that unless performance proves to be an issue.

查看更多
ら.Afraid
3楼-- · 2019-06-24 01:40

Yes, I think its better to use Listener Interface

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

查看更多
登录 后发表回答