Observer pattern
Encyclopedia
The observer pattern is a software design pattern
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...

 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
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

. It is mainly used to implement distributed event handling systems.

Structure

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

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
Gui
Gui or guee is a generic term to refer to grilled dishes in Korean cuisine. These most commonly have meat or fish as their primary ingredient, but may in some cases also comprise grilled vegetables or other vegetarian ingredients. The term derives from the verb, "gupda" in Korean, which literally...

 toolkits.

Some of the most notable implementations of this pattern:

ActionScript

  • flash.events, a package in ActionScript
    ActionScript
    ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

     3.0 (following from the mx.events package in ActionScript 2.0).

C

  • GObject
    GObject
    The GLib Object System, or GObject, is a free software library providing a portable object system and transparent cross-language interoperability...

    , in GLib
    GLib
    GLib is a cross-platform software utility library that began as part of the GTK+ project. However, before releasing version 2 of GTK+, the project's developers decided to separate non-GUI-specific code from the GTK+ platform, thus creating GLib as a separate product...

     - an implementation of objects and signals
    Signal programming
    Signal programming is used in the same sense as dataflow programming, and is similar to event-driven programming.The word signal is used instead of the word dataflow in documentation of such libraries as Qt, GTK+ and libsigc++...

    /callbacks
    Callback (computer science)
    In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine defined in a higher-level layer....

     in C. (This library has many bindings to other programming languages.)

C++

  • libsigc++ - the C++ signalling
    Signal programming
    Signal programming is used in the same sense as dataflow programming, and is similar to event-driven programming.The word signal is used instead of the word dataflow in documentation of such libraries as Qt, GTK+ and libsigc++...

     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
    Signals and slots
    Signals and slots is a language construct introduced in Qt, which makes it easy to implement the Observer pattern while avoiding boilerplate code. The concept is that controls can send signals containing event information Signals and slots is a language construct introduced in Qt, which makes it...

     implementation.
  • libevent - Multi-threaded Crossplatform Signal/Slot C++ Library
  • Boost.Signals, an implementation of signal/slot model
  • MFC
    Microsoft Foundation Class Library
    The Microsoft Foundation Class Library is a library that wraps portions of the Windows API in C++ classes, including functionality that enables them to use a default application framework...

    's CDocument-CView-framework
  • The Qt
    Qt (toolkit)
    Qt is a cross-platform application framework that is widely used for developing application software with a graphical user interface , and also used for developing non-GUI programs such as command-line tools and consoles for servers...

     C++ framework's signal/slot model
    Signals and slots
    Signals and slots is a language construct introduced in Qt, which makes it easy to implement the Observer pattern while avoiding boilerplate code. The concept is that controls can send signals containing event information Signals and slots is a language construct introduced in Qt, which makes it...

  • The Advanced Component Framework
    Advanced Component Framework
    Advanced Component Framework is a C++ component framework created by ImagingTools.Using the built-ACF Compositor tool, the internal application architecture can be visually edited. The front end is based on the Qt GUI framework by Nokia....

    's component-based Model/Observer pattern implementation.
  • The MRPT
    Mobile Robot Programming Toolkit
    The Mobile Robot Programming Toolkit is a cross-platform and open source C++ library aimed to help robotics researchers to design and implement algorithms related to Simultaneous Localization and Mapping , computer vision and motion planning...

     robotics C++ framework's observer/observable model.

Objective C


C#

  • The IObserver Interface - The .NET Framework supported way of implementing the observer pattern.
  • Exploring the Observer Design Pattern - the C# and Visual Basic .NET
    Visual Basic .NET
    Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...

     implementation, using delegates
    Delegate (.NET)
    A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....

     and the Event pattern

ColdFusion

  • http://www.cfdesignpatterns.com/behavioral-patterns/observer-design-pattern-in-coldfusion/
  • http://coldfusioneventmanager.riaforge.org/

Delphi


Java

  • The class java.util.Observer 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, another piece of code provides an implementation of that interface, and another one receives that implementation, and raises events as necessary.

JavaScript

  • JavaScript Observer Pattern. Pocket-sized minimalist framework of common design patterns in JavaScript.
  • EventDispatcher singleton, a JavaScript
    JavaScript
    JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

     core API based Signals and slots
    Signals and slots
    Signals and slots is a language construct introduced in Qt, which makes it easy to implement the Observer pattern while avoiding boilerplate code. The concept is that controls can send signals containing event information Signals and slots is a language construct introduced in Qt, which makes it...

     implementation - an observer concept different from Publish/subscribe
    Publish/subscribe
    Publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers. Published messages are characterized into classes, without knowledge of what, if any, subscribers there may be...

     - pretty lightweighted but still type-safety enforcing.

Lisp

  • Cells, a dataflow extension to Common Lisp
    Common Lisp
    Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

     that uses meta-programming to hide some of the details of Observer pattern implementation.

Perl


PHP

  • Event_Dispatcher, a PHP
    PHP
    PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

     implementation
  • SPL, the Standard PHP Library
  • Symfony Event Dispatcher, a standalone library by the Symfony
    Symfony
    Symfony is a web application framework written in PHP which follows the model-view-controller paradigm. Released under the MIT license, Symfony is free software...

     team

Python

  • Louie, an implementation by Patrick K. O'Brien.
  • PyDispatcher, the implementation on which the Django web framework's signals are based.
  • Py-notify, a Python
    Python (programming language)
    Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

     (plus a little C
    C (programming language)
    C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

    ) implementation
  • Observer Pattern using Weak References implementation by Michael Kent
  • PyPubSub an in-application Pub/Sub library for Observer behavior
  • NotificationFramework classes directly implementing Observer patterns
  • Blinker, an implementation which can be used with decorators.

Ruby

  • Observer, from the Ruby Standard Library.

Other/Misc

  • CSP - Observer Pattern using CSP
    Communicating sequential processes
    In computer science, Communicating Sequential Processes is a formal language for describing patterns of interaction in concurrent systems. It is a member of the family of mathematical theories of concurrency known as process algebras, or process calculi...

    -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 for being too verbose, introducing too many bugs and violating software engineering principles, such as not promoting side-effect
Side effect (computer science)
In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world...

s, encapsulation
Encapsulation (object-oriented programming)
In a programming language encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:* A language mechanism for restricting access to some of the object's components....

, composability
Composability
Composability is a system design principle that deals with the inter-relationships of components. A highly composable system provides recombinant components that can be selected and assembled in various combinations to satisfy specific user requirements...

, separation of concepts, scalability
Scalability
In electronics scalability is the ability of a system, network, or process, to handle growing amount of work in a graceful manner or its ability to be enlarged to accommodate that growth...

, uniformity
Uniformity
Uniformity may refer to:* Distribution uniformity, a measure of how uniformly water is applied to the area being watered* Religious uniformity, the promotion of one state religion, denomination, or philosophy to the exclusion of all other religious beliefs...

, abstraction
Abstraction (computer science)
In computer science, abstraction is the process by which data and programs are defined with a representation similar to its pictorial meaning as rooted in the more complex realm of human life and language with their higher need of summarization and categorization , while hiding away the...

, resource management
Resource management
In organizational studies, resource management is the efficient and effective deployment of an organization's resources when they are needed. Such resources may include financial resources, inventory, human skills, production resources, or information technology...

, semantic distance
Semantic similarity
Semantic similarity or semantic relatedness is a concept whereby a set of documents or terms within term lists are assigned a metric based on the likeness of their meaning / semantic content....

. The recommended approach is to gradually deprecate observers in favor of reactive programming
Reactive programming
In computing, reactive programming is a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will...

 abstractions.

See also

  • Design Patterns (book), the book which gave rise to the study of design patterns in computer science
  • Design pattern (computer science)
    Design pattern (computer science)
    In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...

    , a standard solution to common problems in software design
  • Implicit invocation
    Implicit invocation
    Implicit invocation is a term used by some authors for a style of software architecture in which a system is structured around event handling, using a form of callback...

  • Model-view-controller
    Model-view-controller
    Model–view–controller is a software architecture, currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" from the user interface , permitting independent development, testing and maintenance of each .Model View Controller...

     (MVC)
  • Client–server model

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK