Search code examples
javaswingmodel-view-controllerobserver-pattern

Observer/observable objects with MVC pattern


I have this situation:

An object that it's observable and another object that it is observer.

the observer has a method update(Observable obs,Object obj) that receive through notifyObservers the object changed.when observer receives the notify, update method prints the object changed. I want print out the result in a gui that implements MVC pattern.I'm following this guide MVC pattern. My idea is to make the Controller the observer. something like that:

public class Controller extends AbstractController implements Observer 
{
    public static final String TOTAL_HIT_COUNT_PROPERTY = "Total Hit";

    public void changeTotalHitCount(long new_total_hit_count)
    {
        setModelProperty(TOTAL_HIT_COUNT_PROPERTY, new_total_hit_count);
    }

    @Override
    public void update(Observable o, Object arg) 
    {

    }
}

but I don't know if it's a correct implementation!


Solution

  • Observer Pattern and MVC Pattern are 2 distinct design pattern - just to make sure we are on the same page.

    In the MVC (at least by definition) pattern, the View is supposedly automatically updated when the Model changes, I am guessing this is what you are trying to do. In that situation, that means your Observer should be the View, not the Controller, and your Model will be your Observable object.

    Thus:

    Observable changes --> update Observer
    

    will sort of replicate what you are trying to get in the pure MVC pattern:

    Model changes --> update View
    

    I am not saying this should be the way to do things, but I would think if you try to apply the Java's Observer/Observable to the MVC pattern, this could be on way to go with.