views:

42

answers:

2

Hello, I need a hint concerning MVC and Observer-Pattern.

For example a model contains the classes "Address" and "Person". The Address class contains the fields street:String, zipcode:String, location:String. Whereas the Person class contains the fields name:String, firstName:String, address:Address.

My approach so far looks something like this: Both, Address and Person are observable. If one of their setters is being called, I validate whether the current value and new value differ. Only in this case an update event is fired. The event contains the source, the name of the changed field, the old and the new value.

The class for the view contains text fields to display and edit the information of a person: name, firstname, street, zipcode, location. It knows the Person model and is an subscribed observer for the person. So it gets the update events from the person object.

My questions concerns the address field from type Address in the person class, since an address is observable on its own. If the view gets an update event from person when a new address has been set, I can update all of the address related fields in the view. But what if a field of the address changes? Should the view also register for update events from the address?

Any hints about common design approaches would be appreciated. Greetings.

A: 

IMO the view can register as observer to as many model objects as it wishes to. I don't know of any reasons in general, why an Observer should be limited to observe a single Observable only.

The only problem I see is that since an Observer can only implement the interface once, the same notification method would be used by different observables, which would make handling more awkward.

Moreover, if one Observable is a member of another, the logic to update Observer registrations becomes a bit more tricky.

Péter Török
A: 

I've used JFace databinding quite often and they do it this way:

You create a binding between a model element and a GUI element. To keep it simple, we take a String field in the model a create a binding to a Text object (Textfield) on a GUI. So whenever the value in the model changes, an event is fired, the value may be validated and converted and the Text widget is notified. The binding does the same in the other direction: on every edit on the GUI an event is fired, validated and converted if needed an catched be the observable model field.

So the typical case is that there is a 1:1 relation between a model field and an editor component.

Andreas_D