Cyril Horad
Cyril Horad

Reputation: 1565

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.

Upvotes: 3

Views: 3376

Answers (3)

Adeel Ansari
Adeel Ansari

Reputation: 39887

I don't see any problem,

  • make your model observable, and
  • your controller/s observer

Or introduce a listener, if former doesn't sound good to you.

Upvotes: 1

Twister
Twister

Reputation: 724

Your controlers should just listen to the model. (PropertyChange or something else). Why would you like your controlers to notify themselves ?

If it is the main controller you want to notify it should just listen the model too. Isn't it itself who initialize the model ?

Upvotes: 1

Gorbas
Gorbas

Reputation: 82

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()); 
    }
    

  • Upvotes: 2

    Related Questions