Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 901
Mazzy Avatar asked Mar 06 '26 08:03

Mazzy


2 Answers

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.

like image 170
TS- Avatar answered Mar 07 '26 23:03

TS-


Observer Pattern is part of MVC. It is an integral part of MVC.

The Observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern. Source: https://en.wikipedia.org/wiki/Observer_pattern

The MVC pattern can be seen as a combination of these three design patterns: Observer, Composite, and Strategy Patterns. This means Observer and MVC are compatible.

like image 45
Joel Karunungan Avatar answered Mar 07 '26 22:03

Joel Karunungan



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!