    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Implementing the Observer Pattern in C++ - Part 1</title>
        <link>https://members.accu.org/index.php/journals/372</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #52 - Dec 2002 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c191/">52</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c191-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c191+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Implementing the Observer Pattern in C++ - Part 1</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2002 21:57:50 +00:00 or Mon, 02 December 2002 21:57:50 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;Phil Bass<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e16" id=
"d0e16"></a>Introduction</h2>
</div>
<p>The Observer design pattern is described in the &quot;Gang of Four&quot;
book [<a href="#Gamma">Gamma]</a> as a method of propagating state
changes from a Subject to its Observers. The key feature of the
pattern is that Observers register with the Subject via an abstract
interface. The existence of the registration interface decouples
the Subject from its Observers. This makes the Observer pattern
well suited to a layered architecture in which a lowerlevel Subject
passes information up to its Observers in the layer above.</p>
<p>This idea is so important that I have formulated it as a design
principle:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>Use the Observer Pattern to pass information from a lower layer
to the layer above.</p>
</blockquote>
</div>
<p>With this in mind I developed some C++ library components
intended to support this use of the pattern. These components have
been used extensively in my work at Isotek. They served us well for
nearly two years, but recently we began to find situations in which
they failed to deliver the ease-of-use we expected. The library
itself seemed fine, but unexpected complexities started to arise in
classes using the library components.</p>
<p>In this article I shall describe the Isotek library, illustrate
the situations in which it is awkward to use and begin to explore
ways of tackling its limitations. I hope the library will be of
interest as a partial solution to the problem of implementing the
Observer pattern. A complete solution, however, is left as an
exercise for the reader - because I don't know what it is!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e33" id="d0e33"></a>Library
Overview</h2>
</div>
<p>The Observer support library defines a Subject as any object
that publishes Events. A Subject notifies its Observers of state
changes by generating appropriate Events. A Subject may publish all
state changes through a single Event, or provide separate Events
for different sorts of state change. For example, a Button might
publish a single Event that signals both button-pressed and
button-released state changes, or it might provide both a
button-pressed Event and a buttonreleased Event.</p>
<p>An Observer registers with a Subject by attaching a suitable
function (or function object) to an Event, and unregisters by
detaching the function. The library supports functions taking one
argument or none. In principle it could be extended to use
functions with more arguments but, so far, we have not felt the
need.</p>
<p>Conceptually, an Event is a container of polymorphic functions.
Any function (or function object) that can be called with an
argument of a particular type can be inserted into this container.
So, for example, the following callback functions can all be
inserted into an Event that generates an <span class=
"type">int</span> value:</p>
<pre class="programlisting">
  void f(int); // natural signature
  int g(int); // different return type
  void h(long); // implicit argument
  // conversion
</pre>
<p>Here is some sample code showing the use of the <tt class=
"classname">Event&lt;&gt;</tt> template:</p>
<pre class="programlisting">
  #include &lt;iostream&gt;
  #include &quot;Event.hpp&quot;
  using namespace std;
  // A simple Subject.

  struct Button {
    enum State { released, pressed };

    Button() : state(released) {}

    void press() {
      stateChanged.notify(state=pressed);
    }

    void release() {
      stateChanged.notify(state=released);
    }

    State state;
    Event&lt;State&gt; stateChanged;
  };

  ostream&amp; operator&lt;&lt;(ostream&amp; os,
                      const Button::State&amp; state) {
    return os &lt;&lt; (state == Button::pressed ? &quot;down&quot; : &quot;up&quot;);
  }

  // A callback function.
  void output(Button::State state) {
    cout &lt;&lt; &quot;New state = &quot;
         &lt;&lt; state
         &lt;&lt; endl;
  }

  // A sample program
  int main() {
    Button button;
    cout &lt;&lt; &quot;Initial state = &quot;
         &lt;&lt; button.state &lt;&lt; endl;
    button.stateChanged.attach(output);
    button.press();
    button.release();
    return 0;
  }
</pre>
<p>The <tt class="literal">Button</tt> class is a Subject. It
publishes a single statechanged Event. When the <tt class=
"methodname">Button::press()</tt> function is called the button
goes into the <tt class="literal">Button::pressed</tt> state and it
publishes the state change by calling <tt class=
"methodname">Event&lt;&gt;::notify()</tt>. Similarly, calling
<tt class="methodname">Button::release()</tt> causes another change
of state and this, too, is published by calling <tt class=
"literal">Event&lt;&gt;::notify</tt>.</p>
<p>In this simple example a global function is attached to the
button's state changed event. There are no Observer objects.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e76" id="d0e76"></a>The
Event&lt;&gt; Template Declaration</h2>
</div>
<p>A slightly simplified version of the <tt class=
"classname">Event&lt;&gt;</tt> class template in the library is
shown below.</p>
<pre class="programlisting">
  template&lt;typename Arg&gt;
  class Event {
  public:

    // Iterator type definition.
    typedef ... iterator;

    // Destroy an Event.
    ~Event();

    // Attach a simple function to an
    // Event.
    template&lt;typename Function&gt; iterator attach(Function);

    // Attach a member function to an
    // Event.
    template&lt;class Pointer, typename Member&gt; iterator attach(Pointer, Member);

    // Detach a function from an Event.
    void detach(iterator);

    // Notify Observers that an Event
    // has occurred.
    void notify(Arg) const;

  private:
    ...
  };
</pre>
<p>The template takes a single type argument and the <tt class=
"methodname">notify()</tt> function takes an argument of this type.
Although not shown here, the library provides a specialisation for
<tt class="methodname">Event&lt;void&gt;</tt> in which the
<tt class="methodname">notify()</tt> function takes no
argument.</p>
<p>There are two member template <tt class=
"methodname">attach()</tt> functions. The first accepts a simple
function; the second takes a pointer to an object and a pointer to
a member function of that object. Both <tt class=
"methodname">attach()</tt> function templates create a callback
function object (stored on the heap) and insert a pointer to the
callback into an internal list. This makes it possible to attach a
non-member function, static member function, function object or
member function to the <tt class="classname">Event&lt;&gt;</tt>.
The only restriction is that the function takes an argument
convertible to the Arg type of the Event.</p>
<p>The <tt class="methodname">detach()</tt> function destroys the
callback object specified by the iterator argument and removes the
callback pointer from the list.</p>
<p>The <tt class="methodname">notify()</tt> function simply
iterates through the internal callback list calling each in turn,
passing the parameter value (if any).</p>
<p>Finally, the destructor destroys any callback objects that are
still attached.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e120" id="d0e120"></a>The
Event&lt;&gt; Template Definition</h2>
</div>
<p>The Event implementation uses the External Polymorphism design
pattern. The <tt class="classname">Event&lt;&gt;</tt> classes store
a list of pointers to a function object base class and the
<tt class="methodname">attach()</tt> functions create callback
objects of derived classes. The callbacks contain function pointers
or function objects provided by the client code. The
client-supplied objects need have no particular relationship to
each other. In particular, there is no requirement for the client
object types to be classes or to derive from a common base class.
The callback classes perform the role of an Adapter (see [<a href=
"#Gamma">Gamma</a>]), in effect, adding run-time polymorphism to
the client's function types.</p>
<p>The implementation described here is slightly simpler than the
one in the Isotek library, but it does illustrate all the essential
features of the library implementation. Note that the &quot;<tt class=
"literal">std::</tt>&quot; prefix has been omitted here to save
space.</p>
<pre class="programlisting">
  // Event class template
  template&lt;typename Arg&gt;
  class Event {
    // Function object base class.
    struct AbstractFunction;

    // Concrete function object classes.
    template&lt;typename Function&gt;
    class Callback;

  public:
    // Iterator type definition.
    typedef list&lt;AbstractFunction*&gt;::iterator iterator;
    ...

  private:
    // List of function objects.
    list&lt;AbstractFunction*&gt; callback;
};
</pre>
<p>The library uses the standard list class, which ensures that
iterators are not invalidated by insertions/deletions and callback
functions can be removed efficiently in any order. Both
considerations are important for Subjects that can make no
assumptions about their Observers.</p>
<p><tt class="classname">AbstractFunction</tt> is a simple abstract
base class with a pure virtual function call operator. The
<tt class="classname">Callback</tt> classes are concrete classes
derived from <tt class="classname">AbstractFunction</tt>. They
store a function (as a pointer or function object) and implement
the virtual function call operator by calling the stored the
function. The same basic mechanism is used in Andrei Alexandrescu's
generic functions [<a href="#Alex">Alex</a>]. The <tt class=
"classname">Callback</tt> template, however, is less
sophisticated.</p>
<pre class="programlisting">
  // The function object classes
  // Abstract Function.
  template&lt;typename Arg&gt;
  struct Event&lt;Arg&gt;::AbstractFunction {
    virtual ~AbstractFunction() {}
    virtual void operator()(Arg) = 0;
  };

  // Callback class template.
  template&lt;typename Arg&gt;
  template&lt;typename Function&gt;
  class Event&lt;Arg&gt;::Callback
    : public AbstractFunction {

  public:
    explicit Callback(Function fn) : function(fn) {}

    virtual void operator()(Arg arg) {
      function(arg);
    }

  private:
    Function function;
  };
</pre>
<p>The <tt class="methodname">attach()</tt> functions create a
callback on the heap and insert a pointer to its base class into
the list of function objects. In principle, only the
single-argument <tt class="methodname">attach()</tt> function is
required; the two-argument version is provided for convenience. In
practice, the client code attaches a member function much more
frequently than a simple function, so there is considerable value
in the convenience function.</p>
<pre class="programlisting">
  // The attach() functions
  // Attach a simple function to an Event.
  template&lt;typename Arg&gt;
  template&lt;typename Fn&gt;
  Event&lt;Arg&gt;::iterator Event&lt;Arg&gt;::attach(Fn fn) {
    return callback.insert(callback.end(),
                           new Callback&lt;Fn&gt;(fn));
  }

  // Attach a member function to an Event.
  template&lt;typename Arg&gt;
  template&lt;class P, typename M&gt;
  Event&lt;Arg&gt;::iterator Event&lt;Arg&gt;::attach(P pointer,
                                          M member) {
    return attach(bind1st(mem_fun(member),pointer));
  }
</pre>
<p>The <tt class="methodname">detach()</tt> function destroys the
callback and erases its pointer from the list.</p>
<pre class="programlisting">
  // Detach a callback from an Event.
  template&lt;typename Arg&gt;
  void Event&lt;Arg&gt;::detach(iterator connection) {
    delete(*connection);
    callback.erase(connection);
  }
</pre>
<p>Notifying observers is simply a case of calling each callback in
the list with the supplied parameter (if any). The code in the
library and presented here uses <tt class=
"function">std::for_each()</tt> to iterate through the list. The
function object required as the third parameter of <tt class=
"function">for_each()</tt> is built from the <tt class=
"classname">AbstractFunction</tt>'s function call operator using
<tt class="function">std::mem_fun()</tt> and <tt class=
"function">std::bind2nd()</tt>.</p>
<pre class="programlisting">
  // Notify Observers that an Event has
  // occurred.
  template&lt;typename Arg&gt;
  void Event&lt;Arg&gt;::notify(Arg arg) const {
    typedef AbstractFunction Base;
    for_each(callback.begin(),
             callback.end(),
             bind2nd(mem_fun(&amp;Base::operator()),arg));
  }
</pre>
<p>The final part of the <tt class="classname">Event&lt;&gt;</tt>
template definition is its destructor. It just iterates through the
callback list destroying any callbacks that remain. Again, the code
uses <tt class="function">for_each()</tt> and a simple function
object is defined for use as its third parameter.</p>
<pre class="programlisting">
  // Delete function object.
  struct delete_object {
    template&lt;typename Pointer&gt;
    void operator()(Pointer pointer) {
      delete pointer;
    }
  };

  // Destroy an Event.
  template&lt;typename Arg&gt;
  Event&lt;Arg&gt;::~Event() {
    for_each(callback.begin(),
    callback.end(), delete_object());
  }
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e207" id="d0e207"></a>So Far So
Good, But...</h2>
</div>
<p>When I first wrote the <tt class="classname">Event&lt;&gt;</tt>
template I was aware that copying an Event could cause problems.
Each Event contains a list of pointers that implicitly own the
callback they point to. Copying this list produces two pointers for
each callback, one in the original list and one in the copy.
Destroying one of the lists destroys all the callbacks. Destroying
the second list leads to disaster when the code attempts to destroy
each of the callbacks again.</p>
<p>At the time, it wasn't clear to me how this situation should be
handled. Should the copying of Events be prohibited or should more
appropriate copy semantics be defined? In the end I left the issue
un-addressed on the assumption that any problems would quickly
surface and the hope that specific cases would throw more light on
it. It seems I was wrong on both counts!</p>
<p>The real problems only surfaced when we wanted to store objects
containing Events in standard containers. I shall describe that
scenario in part 2.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e219" id="d0e219"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Gamma" id="Gamma"></a>
<p class="bibliomixed">[Gamma] Gamma, Helm, Johnson and Vlissides,
Design Patterns, Elements of Reusable Object-Oriented Software,
Addison- Wesley, ISBN 0-201-63361-2.</p>
</div>
<div class="bibliomixed"><a name="Alex" id="Alex"></a>
<p class="bibliomixed">[Alex] Andrei Alexandrescu, Modern C++
Design, Addison-Wesley, ISBN 0-201-70431-5.</p>
</div>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
