Tutorial :Observer pattern implementation using Spring dependency injection


I'm trying to develop an application where in the people will get notified if there is any change in the PartNumber. Its a Spring based application. Following is the code snippet.

I've abstracted the storing mechanism here in SaveSubscriptionIF. The actual details of storing and retrieving are in the implementation class of this interface. The implementation class will be injected by Spring.

The external application calls my setState() method- passing the new information.

The store.getObservers() method returns me the Map which have the Observers and the corresponding info to update.

So far so good. Am struck in the implementation part of store.getObservers(). This method implementation needs the state data - i.e the new information passed from the external application.

How do i pass the 'state' data to an implementation class of 'SaveSubscriptionIF'??

public class PartNumberSubject implements Observable {       private SaveSubscriptionIF store;       private Object state;       @Override       public void addObserver(final ObserverIF o, final Object subscriptionDetails) {        store.addObserver(o, subscriptionDetails);       }       @Override       public void notifyObservers() {        @SuppressWarnings("unchecked")        final Map<ObserverIF, List<PartInformationVO>> observers =(Map<ObserverIF,List<PartInformationVO>>) store                 .getObservers();    for (final Entry<ObserverIF, List<PartInformationVO>> observer : observers                          .entrySet()) {       observer.getKey().update(observer.getValue());       }      }      @Override      public void setState(final Object state) {       this.state = state;       notifyObservers();      }      }  


I think I understand what you mean.

Normally in the observer pattern, the value that changed is passed out as a parameter in the Event object that is created.

So, for example, you could create a StateChangedEvent class which had a value in it - state.

Then, your setState method would look like this:

public void setState(final Object state) {      this.state = state;      notifyObservers(state);  }  

And notifyObservers:

public void notifyObservers(Object state) {      StateChangedEvent event = new StateChangedEvent(state);      // Pass this event into each observer which you have subscribed...  }  

I'm sorry if I've misread the question but this seems to be what you're asking.


Passing data to observers is done via the observer's methods. So modify your interface:

public ObserverIF {      void update(List<PartInformationVO>, Object state);  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »