Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad design to have models using both Observer and Observable in Java?

This question pertains to MVC (Model-View-Controller). My Model currently updates my View when it has changed using the Observer / Observable pattern in Java:

public class Model extends Observable {
}

public class View implements Observer {

    @Override
    public void update(observable o, Object obj) {
        // ... update the view using the model.
    }

}

This works fine. However, my model is growing more complex - it's starting to hold Lists of other classes:

public class Model extends Observable {
    List<Person> people = new ArrayList<Person>();
}

public class Person {
    private String name = "";
    // ... getter / setter for name
}

My problem is: when a Person's name changes I want to update the view listening to the model which contains that person. The only way I can think of is to have Model implement an Observer class and have Person extend an Observable class. Then, when Person changes, he notifies his observers (which would include the parent Model).

However, this seems like a lot of work if my models get complex. Are there any better ways to "bubble-up" changes to the parent model?

like image 694
sdasdadas Avatar asked Nov 04 '12 21:11

sdasdadas


1 Answers

First of all usually it is a bad idea to use Observable since you need to extend this class to use it.
In any case what you are describing is an aggregation of observed entities.
Don't complicate simple things. Make each entity an observable and let it take care of registrations and notifications. You don't have to include specifically a class named Model to aggregate everything. Break your design.

like image 88
Cratylus Avatar answered Sep 18 '22 20:09

Cratylus