Observer pattern

Observer pattern

The observer pattern (a subset of the 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

Structure

UML diagram of Observer pattern

Definition

The essence of the Observer Pattern is to "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. ".[1]

Example

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();
    }
}


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:

ActionScript

C

  • GObject, in GLib - an implementation of objects and signals/callbacks in C. (This library has many bindings to other programming languages.)

C++

  • libsigc++ - the C++ signalling template library.
  • sigslot - C++ Signal/Slot Library
  • Cpp::Events - Template-based C++ implementation that introduces separation of connection management interface of the event object from the invocation interface.
  • XLObject - Template-based C++ signal/slot model patterned after Qt.
  • Signals - A lightweight and non-intrusive C++ signal/slot model implementation.
  • libevent - Multi-threaded Crossplatform Signal/Slot C++ Library
  • Boost.Signals, an implementation of signal/slot model
  • MFC's CDocument-CView-framework
  • The Qt C++ framework's signal/slot model
  • The Advanced Component Framework's component-based Model/Observer pattern implementation.
  • The MRPT robotics C++ framework's observer/observable model.

Objective C

C#

ColdFusion

Delphi

Java

  • The class java.util.Observer[2] provides a simple observer implementation.
  • Events are typically implemented in Java through the callback pattern: one piece of code provides a common interface with as many methods as many events are required[3], another piece of code provides an implementation of that interface, and another one receives that implementation, and raises events as necessary.[4]

JavaScript

Lisp

  • Cells, a dataflow extension to Common Lisp that uses meta-programming to hide some of the details of Observer pattern implementation.

Perl

PHP

Python

Ruby

  • Observer, from the Ruby Standard Library.

Other/Misc

  • CSP - Observer Pattern using CSP-like Rendezvous (each actor is a process, communication is via rendezvous).
  • YUI Event utility implements custom events through the observer pattern
  • Publish/Subscribe with LabVIEW, Implementation example of Observer or Publish/Subscribe using G.

Critics

The Observer pattern is criticized[5] for being too verbose, introducing too many bugs and violating software engineering principles, such as not promoting side-effects, encapsulation, composability, separation of concepts, scalability, uniformity, abstraction, resource management, semantic distance. The recommended approach is to gradually deprecate observers in favor of reactive programming abstractions.

See also

References

External links


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

  • Observer Pattern — Der Observer (Beobachter, Listener) ist ein Entwurfsmuster aus dem Bereich der Softwareentwicklung und gehört zu der Kategorie der Verhaltensmuster (Behavioural Patterns). Es dient zur Weitergabe von Änderungen an einem Objekt an von diesem… …   Deutsch Wikipedia

  • Observer — may refer to person who is observing. More specialised meanings follow. Contents 1 Computer science and information theory 2 Fiction 3 Music 4 Physics …   Wikipedia

  • Pattern theory — Pattern theory, formulated by Ulf Grenander, is a mathematical formalism to describe knowledge of the world as patterns. It differs from other approaches to artificial intelligence in that it does not begin by prescribing algorithms and machinery …   Wikipedia

  • Observer effect (physics) — For other uses, see Observer effect. In physics, the term observer effect refers to changes that the act of observation will make on the phenomenon being observed. This is often the result of instruments that, by necessity, alter the state of… …   Wikipedia

  • Observer's Books — The Observer s Books were a series of small, pocket sized books, published by Frederick Warne Co in the United Kingdom from 1937 to 2003. They covered a variety of topics including hobbies, art, history and wildlife. The aim of these books was to …   Wikipedia

  • Pattern — Cette page d’homonymie répertorie les différents sujets et articles partageant un même nom. Sur les autres projets Wikimedia : « Pattern », sur le Wiktionnaire (dictionnaire universel) Le mot anglais « pattern » est… …   Wikipédia en Français

  • Observer-expectancy effect — Participant observer effect redirects here. Psychology …   Wikipedia

  • Design Pattern — Patron de conception Pour les articles homonymes, voir Patron. Un patron de conception (design pattern en anglais) est un concept de génie logiciel destiné à résoudre les problèmes récurrents suivant le paradigme objet. En français on utilise… …   Wikipédia en Français

  • Design pattern — Patron de conception Pour les articles homonymes, voir Patron. Un patron de conception (design pattern en anglais) est un concept de génie logiciel destiné à résoudre les problèmes récurrents suivant le paradigme objet. En français on utilise… …   Wikipédia en Français

  • Behavioral pattern — In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”