Observer pattern

From Wikipedia, the free encyclopedia

Jump to: navigation, search

The observer pattern (a subset of the asynchronous publish/subscribe 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.

Contents

[edit] Examples

Below is an example 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 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
{
    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 obs;
 
import java.util.Observable;
import java.util.Observer;  /* this is Event Handler */
 
public class ResponseHandler implements Observer
{
    private String resp;
    public void update (Observable obj, Object arg)
    {
        if (arg instanceof String)
        {
            resp = (String) arg;
            System.out.println("\nReceived Response: "+ resp );
        }
    }
}
/* Filename : myapp.java */
/* This is the main program */
 
package obs;
 
public class MyApp
{
    public static void main(String args[])
    {
        System.out.println("Enter Text >");
 
        // create an event source - reads from stdin
        final EventSource evSrc = new EventSource();
 
        // create an observer
        final ResponseHandler respHandler = new ResponseHandler();
 
        // subscribe the observer to the event source
        evSrc.addObserver( respHandler );
 
        // starts the event thread
        Thread thread = new Thread(evSrc);
        thread.start();
    }
}

Here is a very basic implementation of the observer pattern in Python:

from collections import defaultdict
 
class Observable (defaultdict):
 
    def __init__ (self):
        defaultdict.__init__(self, object)
 
    def emit (self, *args):
        '''Pass parameters to all observers and update states.'''
        for subscriber in self:
            response = subscriber(*args)
            self[subscriber] = response
 
    def subscribe (self, subscriber):
        '''Add a new subscriber to self.'''
        self[subscriber]
 
    def stat (self):
        '''Return a tuple containing the state of each observer.'''
        return tuple( self.values() )

In the example above, a Python dictionary is overloaded to accept functions as keys whose return values are stored in corresponding slots in the dictionary. Below is a simple illustration. This class could easily be extended with an asynchronous notification method. Although this example stores functions as keys, it is conceivable that one could store user-defined class instances whose methods are accessed in a similar fashion.

myObservable = Observable ()
 
# subscribe some inlined functions.
# myObservable[ lambda x,y: x*y ] would also work here.
myObservable.subscribe( lambda x,y: x*y )
myObservable.subscribe( lambda x,y: float(x)/y )
myObservable.subscribe( lambda x,y: x+y )
myObservable.subscribe( lambda x,y: x-y )
 
# emit parameters to each observer
myObservable.emit (6, 2)
 
# get updated values
myObservable.stat ()         # returns: (8, 3.0, 4, 12)

[edit] Implementations

The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits.

Some of the most notable implementations of this pattern:

[edit] References

[edit] See also

[edit] External links

Personal tools