Skip to content
Advertisement

How to observe different attributes of same types with the Observer pattern?

I implemented the Observer pattern in an MVC application so a bean can listen for changes in the model. Since I’m in Java8 I’m using Observer and Observable from Java.util. Here’s part of what I coded:

JavaScript

I think the implementation is correct because, in a simple test that I made, the changes to Ids and Names are correctly read by the bean class, but I realized that I can’t listen for changes of the email attributes because in the bean class I’m using ‘instanceof’ to understand which value I have to update.

There’s a way to recognize which variable has changed? I should implement my own version of the Observer and Observable classes instead of using Java.Util? I think that with the second solution I could define an update method for every attribute but I don’t know how to manage the synchronization process in Java.

Advertisement

Answer

The first argument in the update method is an Observable. That is your UserModel object that has changed, so it contains all the updated data. So instead of using the second parameter to pass the new value of an object you can use it to pass the name of the object that has changed (or use an enum because it’s a bit cleaner).

A solution could look like this:

UserBean:

JavaScript

UserModel:

JavaScript

Note: Like mentioned in the comments a generic approach would be better, to avoid the object casts. It could be used similar to this implementation. Just add some generic parameters, but the idea stays the same.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement