Observer pattern

From Wikipedia, the free encyclopedia
  (Redirected from Observer Pattern)
Jump to: navigation, search

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. The Observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern.[1] The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits.

The observer pattern can cause memory leaks, known as the lapsed listener problem, because in basic implementation it requires both explicit registration and explicit deregistration, as in the dispose pattern, because the subject holds strong references to the observers, keeping them alive. This can be prevented by the subject holding weak references to the observers.

Related patterns: Publish–subscribe pattern, mediator, singleton.

Structure[edit]

UML class diagram of Observer pattern

Example[edit]

Below is an example written in Java that takes keyboard input and treats each input line as an event. The example is built upon the library classes java.util.Observer and java.util.Observable. When a string is supplied from System.in, the method notifyObservers is then called, in order to notify all observers of the event's occurrence, in the form of an invocation of their 'update' methods - in our example, ResponseHandler.update(...).

The file MyApp.java contains a main() method that might be used in order to run the code.

/* File Name : EventSource.java */
package org.wikipedia.obs;
 
import java.util.Observable;          //Observable is here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class EventSource extends Observable implements Runnable {
    @Override
    public void run() {
        try {
            final InputStreamReader isr = new InputStreamReader(System.in);
            final BufferedReader br = new BufferedReader(isr);
            while (true) {
                String response = br.readLine();
                setChanged();
                notifyObservers(response);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/* File Name: ResponseHandler.java */
 
package org.wikipedia.obs;
 
import java.util.Observable;
import java.util.Observer;  /* this is Event Handler */
 
public class ResponseHandler implements Observer {
    @Override
    public void update(Observable obj, Object arg) {
        if (arg instanceof String) {
            String resp = (String) arg;
            System.out.println("\nReceived Response: " + resp );
        }
    }
}
/* Filename : MyApp.java */
/* This is the main program */
 
package org.wikipedia.obs;
 
public class MyApp {
    public static void main(String[] args) {
        System.out.println("Enter Text >");
 
        // create an event source - reads from stdin
        final EventSource eventSource = new EventSource();
 
        // create an observer
        final ResponseHandler responseHandler = new ResponseHandler();
 
        // subscribe the observer to the event source
        eventSource.addObserver(responseHandler);
 
        // starts the event thread
        Thread thread = new Thread(eventSource);
        thread.start();
    }
}


A similar example in Python:

class Observable(object):
  def __init__(self):
    self.__observers = []
  def registerObserver(self, observer):
    self.__observers.append(observer)
  def notifyObservers(self, *args, **kwargs):
    for observer in self.__observers:
      observer.notify(self, *args, **kwargs)
 
class Observer(object):
  def __init__(self, observable):
    observable.registerObserver(self)
  def notify(self, observable, *args, **kwargs):
    print 'Got', args, kwargs, 'From', observable
 
subject = Observable()
observer = Observer(subject)
subject.notifyObservers('test')

See also[edit]

References[edit]

  1. ^ "Model-View-Controller". MSDN. Retrieved 01/06/2013.  Check date values in: |accessdate= (help)

External links[edit]