티스토리 뷰

The observer pattern (sometimes known as publish/subscribe) is a design pattern used in computer programming to observe the state of an object in a program. It is related to the principle of implicit invocation.

This pattern is mainly used to implement a distributed event handling system. In some programming languages, the issues addressed by this pattern are handled in the native event handling syntax. This is a very interesting feature in terms of real-time deployment of applications.

The essence of this pattern is that one or more objects (called observers or listeners) are registered (or register themselves) to observe an event which may be raised by the observed object (the subject). (The object which may raise an event generally maintains a collection of the observers.)

The UML diagram below illustrates this structure:

Image:observer-pattern-uml.jpg

Contents

[hide]

[edit] Participant classes

The participants of the pattern are detailed below. Member functions are listed with bullets.

[edit] Subject

This class provides an interface for attaching and detaching observers. Subject class also holds a private list of observers. Contains these functions:

  • Attach - Adds a new observer to the list of observers observing the subject.
  • Detach - Removes an observer from the list of observers observing the subject.
  • Notify - Notifies each observer by calling the notify() function in the observer, when a change occurs.

[edit] ConcreteSubject

This class provides the state of interest to observers. It also sends a notification to all observers, by calling the Notify function in its super class (i.e, in the Subject class). Contains this function:

  • GetState - Returns the state of the subject.

[edit] Observer

This class defines an updating interface for all observers, to receive update notification from the subject. The Observer class is used as an abstract class to implement concrete observers. Contains this function:

  • Notify - An abstract function, to be overriden by concrete observers.

[edit] ConcreteObserver

This class maintains a reference with the ConcreteSubject, to receive the state of the subject when a notification is received. Contains this function:

  • Notify - This is the overridden function in the concrete class. When this function is called by the subject, the ConcreteObserver calls the GetState function of the subject to update the information it has about the subject's state.

When the event is raised each observer receives a callback. This may be either a virtual function of the observer class (called 'notify()' on the diagram) or a function pointer (more generally a function object or "functor") passed as an argument to the listener registration method. The notify function may also be passed some parameters (generally information about the event that is occurring) which can be used by the observer.

Each concrete observer implements the notify function and as a consequence defines its own behavior when the notification occurs.

[edit] Typical usages

The typical usages of the observer pattern:

  • Listening for an external event (such as a user action). See Event-driven programming.
  • Listening for changes of the value of an object property.
  • In a mailing list, where every time an event happens (a new product, a gathering, etc.) a message is sent to the people subscribed to the list.

The observer pattern is also very often associated with the model-view-controller (MVC) paradigm. In MVC, the observer pattern is used to create a loose coupling between the model and the view. Typically, a modification in the model triggers the notification of model observers which are actually the views.

[edit] C# Implementations

/* First create an two interfaces that will encapsulate the methods of a subject including:<br />
 * ISubject --> interface for the subject<br />
 * RegisterObserver(IObserver observer); used to register an observer to the subject's notification list<br />
 * UnregisterObserver(IObserver observer); used to remove a registered observer from the subject's notification list<br />
 * NotifyObservers(); used to notify the observers in the notification list of any change that occurred in the subject<br />
 */
public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void UnregisterObserver(IObserver observer);
    void NotifyObservers();
}
/* IObserver --> interface for the server<br />
 * Update(); called by the subject to update the observer of any change<br />
 * The method parameters can be modified to fit certain criteria<br />
 */
public interface IObserver
{
    void Update();
}
// Subject --> class the implements the ISubject interface.... 
using System.Collections;
 
public class Subject : ISubject
{
    //use array list implementation for collection of observers
    ArrayList observers;
 
    //decoy item to use as counter
    int counter;
 
    //constructor
    public Subject()
    {
        observers = new ArrayList();
        counter = 0;
    }
 
    public void RegisterObserver(IObserver observer)
    { 
        //if list does not contain observer, add
        if(!observers.Contains(observer)
        {
             observers.Add(observer);
        }
    }
 
    public void UnregisterObserver(IObserver observer)
    {
        //if observer is in the list, remove
        if(observers.Contains(observer))
        {
            observers.Remove(observer);   
        }
    }
 
    public void NotifyObservers() 
    {
        //call update method for every observer
        foreach(IObserver observer in observers)
        {
            observer.Update();
        }
    }
 
    //use function to illustrate observer function
    //the subject will notify only when the counter value is divisible by 5
    public void Operate()
    {
        for(counter = 0; counter < 26; counter++)
        {
            if(counter % 5 == 0)
            {
                NotifyObservers();
            }
        }
    }
}
// Observer --> Implements the IObserver
public class Observer :IObserver
{
    //this will count the times the subject changed
    //evidenced by the number of times it notifies this observer
    int counter;
 
    public Observer()
    {
        counter = 0;
    }
 
    //counter is incremented with every notification
    public void Update() 
    {
         counter += 1;
    }
 
    //a getter for counter
    public int Counter
    {
        get
        {
            return counter;
        }
    }
}
//TESTER
using System;
 
public class ObserverTester
{
    [STAThread]
    public static void Main()  
    {
        Subject mySubject = new Subject();
        Observer myObserver1 = new Observer();
        Observer myObserver2 = new Observer();
 
        //register observers
        mySubject.RegisterObserver(myObserver1);
        mySubject.RegisterObserver(myObserver2);
 
        mySubject.Operate();
 
        //both observers are expected to yield 5 as a result of 5 notifications 
        Console.WriteLine("Observer 1 : {0} notifications.",myObserver1.Counter);
        Console.WriteLine("Observer 2 : {0} notifications.",myObserver2.Counter);
    }
}

[edit] Pseudocode

This pseudocode, written in a Python-esque syntax, demonstrates the observer pattern.

class Listener:
    def __init__(self, name, subject):
        self.name = name
        subject.register(self)

    def notify(self, event):
        print self.name, "received event", event
class Subject:
    def __init__(self):
        self.listeners = []

    def register(self, listener):
        self.listeners.append(listener)

    def unregister(self, listener):
        self.listeners.remove(listener)

    def notify_listeners(self, event):
        for listener in self.listeners:
            listener.notify(event)
subject = Subject()
listenerA = Listener("<listener A>", subject)
listenerB = Listener("<listener B>", subject)
# the subject now has two listeners registered to it.
subject.notify_listeners ("<event 1>")
# outputs:
#     <listener A> received event <event 1>
#     <listener B> received event <event 1>

[edit] Implementations

Here is an example that takes keyboard input and treats the input line as an Event. The native method notifyObserver 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
{
   String response;
   public void run()
   {
      try
      {   
          InputStreamReader isr = new InputStreamReader(System.in);
          BufferedReader br = new BufferedReader(isr);
          while( true )
          {
               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 main program */
 
package OBS;
 
public class myapp
{
      public static void main(String args[])
      {            
            System.out.println("Enter Text >");
            EventSource evSrc = new EventSource();
            ResponseHandler respHandler = new ResponseHandler();
            evSrc.addObserver(respHandler);
            evSrc.run();     
      }
}


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] See also

[edit] External links

scope/Purpose Creational Structural Behavioral
Class Factory Method Adapter Interpreter
Class Template Method
Object Abstract Factory Adapter Chain of Responsibility
Object Factory Bridge Command
Object Builder Composite Iterator
Object Prototype Decorator Mediator
Object Singleton Facade Memento
Object Flyweight Observer
Object Proxy State
Object Strategy
Object Visitor

'IT > 프로그래밍' 카테고리의 다른 글

Volatile [펌 www.debuglab.com]  (0) 2007.12.18
가변인자(...) va_start, va_arg, va_end  (0) 2007.11.18
Java Guide - Abstraction and Interfaces  (0) 2007.07.31
Java Guide - Polymorphism  (0) 2007.07.31
Java Guide - Polymorphism  (0) 2007.07.31
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함