Search code examples
javaandroidmodel-view-controllerobserver-pattern

Observer Pattern in MVP


I have a System (game) which I try to implement using the architecture Model-View-Presenter. What I have done right now is a while loop in the presenter that calls continuously the view methods for displaying. The way I do this is using a Producer/Consumer pattern, where the View register and event handler for touch events(Android) and produce the corresponding touch imstances, that the presenter consumes in the while loop.

Now I would like to use the pattern Observer/Suscriber between The Model and the Presenter. Using this the Presenter will be the Observer subscribe to changes on the state of the Model. The thing is, the presenter will execute the updates in the model, accordingly to the events occurred in the view. Every time that the presenter executes one method in.the model, It will be. possible to change its state and notify the presenter. I will separate then in another thread the model for every update, but how can I notify the presenter if this is running in a different thread inside a while loop? If I call the method notify observers, when the presenter will call the corresponding method?

Its driving me crazy! :P I need your help captains!


Solution

  • It Doesn't matter. You have an object, Presenter, which is being used inside an infinite loop inside a thread. That does not mean you cannot call it's methods while its being called by the thread as well. The only consideration you have to take care of is that, if the data being read/used by the thread is the same altered by the observer notification, you shoud synchronize it access.

    So, to summarize, while the Presenter is running inside the infinite loop, any call to it's method will be answered instantly (unless they have synchronized access, in which case it will block until it gets the lock ownership)

    The following is completly fine:

    class Presenter implements IObserver
    {
        public void aMethod() { }
    
        public void notifyObserver() { }
    }
    
    class Model
    {
        private List<IObserver> observers = new ArrayList<>();
    
        public void addObserver(IObserver obs) { observers.add(obs); }
    
        public void notifyObservers()
        {
            for(IObserver o : observers) { o.notifyObserver(); }
        }
    }
    
    
    final Presenter myPresenter = new Presenter();
    Model myModel = new Model();
    myModel.add(myPresenter);
    
    new Thread(new Runnable() 
    {
        @Override
        public void run()
        {
            while(true)
            {
                myPresenter.aMethod();
            }           
        }
    ).start();