Observer pattern

From Wikipedia, the free encyclopedia
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.


UML class diagram of Observer pattern


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, 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.

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

/* Filename: */
package org.wikipedia.obs;
import java.util.Observable;          // Observable is here
public class EventSource extends Observable implements Runnable {
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(;
            while (true) {
                String response = br.readLine();
        } catch (IOException e) {
/* Filename: */
package org.wikipedia.obs;
import java.util.Observable;          // Observable is here
import java.util.Observer;
import static java.lang.System.out;
public class MyApp {
    public static void main(String[] args) {
        out.println("Enter Text >");
        // instance EventSource class
        EventSource eventSource = new EventSource();
        // create an observer
        Observer responseHandler = (Observable obj, Object arg) -> { 
            out.println("\nReceived response: " + arg);
        // subscribe the observer to the EventSource instance
        // starts the event thread
        new Thread(eventSource).start();

A similar example in Python:

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

See also[edit]


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

External links[edit]