Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java MVC-pattern with Observer/Observable

Greetings,

I have a problem in my application I'm building in. To give the scenario I'm in. I have these two controllers both inherit the same model initialize from a main controller. All controllers have their on views but I have only one model.

To problem is that. When ever changes happens to that model. How can I notify the other controller (from the two controllers) that an update occurred? I'm a going to use Observer/Observable or PropertyChangeEvent? And how, I'm a little bit of confused on implement both on the MVC archictecture.

Your response is highly appreciated on this matter.

Thanks, Cyril H.

like image 789
Cyril Horad Avatar asked May 08 '26 02:05

Cyril Horad


1 Answers

I had a similar case where I used PropertyChangeSupport in order to listen to model's changes. I believe that the best way is to create an AbstractEntity that contains a private PropertyChangeSupport and two public methods addPropertyListener, removePropertyListener and a protected method firePropertyChange. Those methods will be used as wrappers of the PropertyChangeSupport's ones. So your controllers should just addPropertyListeners in order to listen to changes of the common model.

Note:

  • You should use the same instance of model accross all the controlers.
  • The classes that you need are the following:
  • java.beans.PropertyChangeSupport
  • java.beans.PropertyChangeListener

  • Example code for how the
  • public void setValue(String value){
          String oldValue=getValue();
          this.value=value;
          firePropertyChange("value",oldValue,getValue()); 
    }
    

    like image 107
    Gorbas Avatar answered May 09 '26 16:05

    Gorbas



    Donate For Us

    If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!