I’ll talk now a little about the observer design pattern, or i can call it the listener design pattern.

the Observer design pattern define a one-to-many relationship between objects that when an object status changes the other dependent objects be notified.

the idea is : there is an object that has a peace of information, many other objects interested in knowing when its state changes.

the way to handle this is creating a way to allow dependent objects to register to be notified when the status changes. here is an imagination of how you can model this situation:

Class Diagram

Class Diagram

From the diagram you can see that we created two interfaces one for the subject object which will contains the information or status other objects needed to be aware about. the Subject interface has 3 methods registerObserver, deregisterObserver and notifyObservers.

registerObserver(): takes an Observer object as a argument and add this object to an internal arraylist or whatever you choose to keep all registered observers on it.

deregisterObserver(): takes an Observer object as a argument and and remove this object from the observers arraylist.

notifyObservers(): call the update() method on all observers exists on the observers arraylist and send the new status(s) as arguments.

The Observer Interface contains one method update()

update(): this method takes the status or information it interested in as argument(s).

so in pref. an subject object has information some observer objects interested in, so the observer objects register themselves on the subject object by calling the register method.

when the data in the subject object changed the notifyObservers() method call and it send the new information by calling update method in all registered observers.

when an observer object decided to stop receiving updates it deregister himself from the subject object by calling deregister() on the subject object.

Advertisements