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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With