    <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  :: Evolution of the Observer Pattern</title>
        <link>https://members.accu.org/index.php/journals/250</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 #64 - Dec 2004 + Design of applications and programs</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/c148/">64</a>
                    (5)
<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/c67/">Design</a>
                    (236)
<br />

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

                    -                        <a href="https://members.accu.org/index.php/journals/c148+67/">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;Evolution of the Observer Pattern</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 12 December 2004 15:57:10 +00:00 or Sun, 12 December 2004 15:57:10 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>Back in the early 1990s four wise men began a voyage of
discovery. They were trying to trace the origins of good software
design. They crossed great deserts of featureless software and
fought through almost impenetrable jungles of code. What they found
changed the way we think about software development. Eric Gamma,
Richard Helm, Ralph Johnson and John Vlissides discovered a
plethora of Design Pattern species falling into 23 separate
genera.</p>
<p>The &quot;Gang of Four&quot;, as they have become known, published their
findings in 1995 [<a href="#GoF">GoF</a>] and &quot;patternologists&quot;
have been studying these creatures ever since. I have taken a
particular interest in the Observer pattern and I have evidence for
changes in its morphology and behaviour. The Observer pattern is
evolving rapidly and this paper presents some recent and, I
believe, important changes.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e27" id="d0e27"></a>Historical
Perspective</h2>
</div>
<p>In their description of the Observer pattern the Gang of Four
assumed that a Subject has a single point of attachment and that
Observers attach directly to their Subjects. I have argued
([<a href="#Bass2002">Bass2002</a>], [<a href=
"#Bass2003">Bass2003</a>]) that Subjects can have multiple
attachment points (Events) and that Observers may attach indirectly
via structures known as Callbacks. Indeed, it is possible to
understand the Observer pattern purely in terms of Events and
Callbacks. From this perspective, a Subject is anything that
publishes Events and an Observer is anything that attaches
Callbacks to Events.</p>
<p>Formally, a Subject provides registries of event handlers, while
Observers add handlers to these registries and subsequently remove
them again. State change events in a Subject are communicated to
the Observers by calling the registered handlers. In this paper,
however, we will use 'Event' to mean &quot;registry of event handlers&quot;
and 'Callback' to mean &quot;registered event handler&quot;. This terminology
is slightly unusual, but it simplifies the discussion
considerably.</p>
<p>In the Gang of Four pattern, detaching an Observer required the
Subject to search its collection of attached Observers. I proposed
a more efficient mechanism in which the Observer stores an iterator
returned when a Callback is attached to an Event and passes the
iterator back to the Event when the Callback is detached. Although
more efficient, this approach requires more client code and is more
vulnerable to programmer error. (I call this the correctness vs.
efficiency problem.)</p>
<p>Until recently, my own research has been confined to Events
based on lists of pointers to a polymorphic callback base class.
For example, here is a complete specimen of the common Event
(<span class="emphasis"><em>Eventus
Vulgaris</em></span>)<sup>[<a name="d0e47" href="#ftn.d0e47" id=
"d0e47">1</a>]</sup> as described in [<a href=
"#Bass2003">Bass2003</a>].</p>
<pre class="programlisting">
// Abstract Function interface class.
template&lt;typename Arg&gt;
struct AbstractFunction {
  virtual ~AbstractFunction() {}
  virtual void operator() (Arg) = 0;
};
// Event class template.
template&lt;typename Arg&gt;
struct Event : list&lt;AbstractFunction&lt;Arg&gt;*&gt; {
  void notify(Arg arg) {
    typedef AbstractFunction&lt;Arg&gt; Func;

    for_each(begin(), end(),
           bind2nd(mem_fun(&amp;Func::operator()),
                   arg));
  }
};
</pre>
<p><span class="bold"><b>Specimen 1 - An Event from early
2003</b></span></p>
<p>We will compare this with several specimens of a newly
discovered species (<span class="emphasis"><em>Eventus
Adaptabilis</em></span>) that is able to use different types of
container and different types of callback. These adaptive changes
allow <span class="emphasis"><em>E. Adaptabilis</em></span> to
thrive in a much wider range of programming environments. They also
provide a solution to the correctness vs. efficiency problem, as we
shall see shortly.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e70" id="d0e70"></a>A Remarkable
New Species</h2>
</div>
<p>The key to the greater adaptability of <span class=
"emphasis"><em>E. Adaptabilis</em></span> is a second template
parameter, which specifies the type of container and, hence, the
type of the callback pointers stored within it.</p>
<pre class="programlisting">
template&lt;
    typename Arg,
    typename Container =
        std::list&lt;Callback::Function&lt;Arg&gt;*&gt; &gt;
struct Event;
</pre>
<p><span class="bold"><b>Specimen 2 - The defining feature of
Eventus Adaptabilis.</b></span></p>
<p>This tiny fragment suggests answers to several questions that
have puzzled patternologists. It explains, for example, why most
<span class="emphasis"><em>E. Adaptabilis</em></span> individuals
are almost indistinguishable from their <span class=
"emphasis"><em>E. Vulgaris</em></span> cousins. Because, by
default, <span class="emphasis"><em>E. Adaptabilis</em></span> uses
the same container type as <span class="emphasis"><em>E.
Vulgaris</em></span> the two species often have identical external
appearance and behaviour. It is also clear from this fragment how
<span class="emphasis"><em>E. Adaptabilis</em></span> is able to
adapt so easily to different environments. Simply by specifying a
different <tt class="classname">Container</tt> argument
<span class="emphasis"><em>E. Adaptabilis</em></span> can acquire
any of the characteristics of that <tt class=
"classname">Container</tt>.</p>
<p>It is not clear, however, from Specimen 2 whether <span class=
"emphasis"><em>E. Adaptabilis</em></span> acquires its behavioural
traits through inheritance, nor can we deduce which types of
container constitute valid parameters to the <span class=
"emphasis"><em>E. Adaptabilis</em></span> template. To answer such
questions we must look inside the Event. Our next specimen is
instructive, here.</p>
<pre class="programlisting">
template&lt;typename Arg, typename Container&gt;
struct Event : Container {
  struct notify_function {
    notify_function(Arg a) : arg(a) {}
    typedef typename
            element&lt;Container&gt;::type pointer;
    void operator()(const pointer&amp; ptr)
                               {(*ptr)(arg);}
    Arg arg;
  };
  // ...  indistinct features
  void notify(Arg arg) {
    // for_each(begin(), end(),
    //          notify_function(arg)); ???
  }
};
</pre>
<p><span class="bold"><b>Specimen 3 - Some internal structure of E.
Adaptabilis.</b></span></p>
<p>Unfortunately, the details of the <tt class=
"function">notify()</tt> function have not been preserved. When
this specimen was first discovered we assumed that the <tt class=
"function">notify()</tt> function is similar to that of
<span class="emphasis"><em>E. Vulgaris</em></span>, as shown by the
comment. In fact, this assumption turned out to be incorrect, but
Specimen 3 does clearly show several interesting features. It is
immediately clear, for example, that <span class="emphasis"><em>E.
Adaptabilis</em></span> inherits all the characteristics of its
<tt class="classname">Container</tt>.</p>
<p>The most striking feature of Specimen 3, however, is the nested
function object class, <tt class="classname">notify_function</tt>.
It is perfectly adapted to its assumed role in the <tt class=
"function">notify()</tt> function. It provides exactly the right
interface for the <tt class="function">for_each()</tt> algorithm
and yet makes only the minimum assumptions about the container
element types. Where <span class="emphasis"><em>E.
Vulgaris</em></span> is restricted to using <tt class=
"classname">std::list&lt;&gt;</tt>, <span class="emphasis"><em>E.
Adaptabilis</em></span> is free to use vectors, lists, sets,
user-defined containers, etc. And where <span class=
"emphasis"><em>E. Vulgaris</em></span> requires the container
element type to be a built-in pointer to an <tt class=
"classname">AbstractFunction&lt;Arg&gt;</tt>, <span class=
"emphasis"><em>E. Adaptabilis</em></span> accepts built-in pointers
and smart pointers to ordinary functions and function objects of
any type that can be called with an argument convertible to
<i class="parameter"><tt>Arg</tt></i>.</p>
<p>It is interesting to note that the <tt class=
"classname">notify_function</tt> is public and, therefore,
available to client code. This seems to be a violation of
encapsulation, but it also provides benefits, as we shall see
later.</p>
<p>Another note-worthy feature of the <tt class=
"classname">notify_function</tt> is the <tt class=
"function">element&lt;Container&gt;</tt> meta-function. The
implementation of this meta-function was missing from Specimen 3,
but an intact sample was discovered later and is shown here as
Specimen 4.</p>
<pre class="programlisting">
template&lt;typename Container&gt;
struct element {
  typedef typename Container::value_type type;
};
</pre>
<p><span class="bold"><b>Specimen 4 - The element
meta-function.</b></span></p>
<p>In itself this is an unremarkable structure. It just extracts
the <tt class="varname">value_type</tt> from a container that
conforms to the standard requirements. In evolutionary terms,
however, its existence is quite interesting. <span class=
"emphasis"><em>E. Adaptabilis</em></span> can only benefit from the
<tt class="classname">element&lt;&gt;</tt> meta-function when it
uses a non-standard container and only then if the meta-function is
specialised for that container. As yet, there are no known cases of
<span class="emphasis"><em>E. Adaptabilis</em></span> and
non-standard containers co-existing like this in the wild. It must
be a matter of speculation, therefore, whether this feature has any
real benefit.</p>
<p>The internal structure of the <tt class="function">notify()</tt>
function was a surprise. Instead of the ubiquitous <tt class=
"function">for_each()</tt> function it uses a hitherto unknown
algorithm, <tt class="function">slither()</tt>. The notify()
function can be seen in Specimen 5 and the <tt class=
"function">slither()</tt> algorithm itself is shown in Specimen
6.</p>
<pre class="programlisting">
template&lt;typename Arg, typename Container&gt;
struct Event : Container {
  // ...

  void notify(Arg arg) {
    slither(this-&gt;begin(),
            this-&gt;end(),
            notify_function(arg));
  }
};
</pre>
<p><span class="bold"><b>Specimen 5 - E. Adaptabilis notify()
function.</b></span></p>
<pre class="programlisting">
template&lt;typename Iterator, typename Function&gt;
void slither(Iterator first, Iterator last,
             Function function) {
  if(first != last) {
    for(Iterator next = first;
        ++next != last;) {
      function(*first), first = next;
    }
    function(*first);
  }
}
</pre>
<p><span class="bold"><b>Specimen 6 - The slither()
algorithm.</b></span></p>
<p>Like <tt class="function">for_each()</tt>, <tt class=
"function">slither()</tt> applies a given function to the result of
dereferencing every iterator in the range <tt class=
"literal">[first, last)</tt>. However, <tt class=
"function">slither()</tt> uses two iterators. At the start of the
for loop body first points to the function about to be called and
next points to the next one. At that point the function is called,
first is moved forward to next <span class="emphasis"><em>by
assignment</em></span>, and next is incremented. The loop then
proceeds to the next iteration or terminates. The overall effect is
the same as <tt class="function">for_each()</tt> and yet the
algorithm is more complex.</p>
<p>Patternologists puzzled over this for a long time. Natural
selection is a powerful mechanism for reducing the costs associated
with unnecessary complexity. It should prefer <tt class=
"function">for_each()</tt> over <tt class=
"function">slither()</tt>. And yet here was an example of evolution
proceeding in the wrong direction. Several explanations were
proposed to account for this anomaly. Perhaps <tt class=
"function">slither()</tt> is just a transient mutation that hasn't
yet been weeded out by competition with <tt class=
"function">for_each()</tt>. Or, perhaps there is some hidden
benefit to <tt class="function">slither()</tt> that more than
compensates for the cost.</p>
<p>I have made a crude attempt to measure the relative costs of
<tt class="function">for_each()</tt> and <tt class=
"function">slither()</tt>. As is often the case when measuring
speed of execution I found the result surprising. There was no
difference in speed between the two algorithms. (I used GCC 3.2.3
on Linux Red Hat 9 with full optimisation.) In fact, my attempt to
extend the running time by increasing the number of function
pointers in the container just consumed all the available RAM and
triggered swapping, which made further measurements meaningless.
However, I saw approximately 200 million loop iterations per second
on my 700 MHz PC before swapping kicked in. I tentatively
concluded, therefore, that there is no significant cost associated
with the <tt class="function">slither()</tt> algorithm.</p>
<p>The negligible cost of <tt class="function">slither()</tt> may
explain how it manages to compete with <tt class=
"function">for_each()</tt>, but it doesn't explain why it came into
existence. For that we need to look at <span class=
"emphasis"><em>E. Adaptabilis</em></span> in a hostile environment.
Consider the following sample program:</p>
<pre class="programlisting">
#include &quot;Event.hpp&quot;
// Callback that detaches itself from the
// event when called.
struct Disconnect : Callback::Function&lt;int&gt; {
  Disconnect(Event&lt;int&gt;&amp; e)
    : event(e),
      position(e.insert(e.end(),this)) {}
  void operator()(int i) {
    event.erase(position);
  }
  Event&lt;int&gt;&amp;          event;
  Event&lt;int&gt;::iterator position;
};
int main() {
  Event&lt;int&gt; event;
  Disconnect disconnect(event);
  event.notify(7);   // !
  event.notify(7);
  return 0;
}
</pre>
<p><span class="bold"><b>Specimen 7 - E. Adaptabilis in a hostile
environment.</b></span></p>
<p>Here we have a callback that connects itself to an event in its
constructor and disconnects itself when it is called. Such
callbacks are extremely poisonous to <span class="emphasis"><em>E.
Vulgaris</em></span>, but <span class="emphasis"><em>E.
Adaptabilis</em></span> is immune. To see why, consider the
<tt class="function">Event::notify()</tt> call. <span class=
"emphasis"><em>E. Vulgaris</em></span> iterates through its list of
callback pointers using <tt class="function">for_each()</tt> which
(invariably) increments a single iterator. When the iterator
reaches a <tt class="classname">Disconnect</tt> callback <tt class=
"function">for_each()</tt> invokes the callback, which erases
itself from the list, invalidating the iterator. The <tt class=
"function">for_each()</tt> algorithm then tries to increment the
invalid iterator and continue the sequence of function calls,
typically with disastrous results. <span class="emphasis"><em>E.
Adaptabilis</em></span>, however, uses the <tt class=
"function">slither()</tt> algorithm. When it gets to the <tt class=
"classname">Disconnect</tt> callback it invokes the callback, which
erases itself from the list, invalidating the iterator as before.
But <tt class="function">slither()</tt> doesn't increment the
invalid iterator, it simply assigns a new value to it. This is, of
course, a valid operation, so the algorithm completes normally and
<span class="emphasis"><em>E. Adaptabilis</em></span> lives to
notify another event.</p>
<p>Together these features provide an answer to the question of
what constitutes a valid <tt class="classname">Container</tt>
argument to the <span class="emphasis"><em>E.
Adaptabilis</em></span> template, <tt class=
"classname">Event&lt;Arg,Container&gt;</tt>. The <tt class=
"classname">Container</tt> must be a class with <tt class=
"function">begin()</tt> and <tt class="function">end()</tt> member
functions returning Forward iterators. It must contain a nested
typedef, <tt class="type">value_type</tt>, that defines the type of
the container elements, or it must provide a specialisation of the
<tt class="classname">element&lt;&gt;</tt> meta-function for that
purpose. The element type must define a dereference operation. And
the result of dereferencing an element must be a function or
function object that can be called with an argument of type
<tt class="classname">Arg</tt>.</p>
<p>These are very general requirements. They can be summarised
informally as:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>An <span class="emphasis"><em>E. Adaptabilis</em></span> event
is a container of pointers to functions.</p>
</li>
<li>
<p>In this context, a pointer is any type that can be
dereferenced;</p>
</li>
<li>
<p>And a function is any type that can be called with an argument
of the right type.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e376" id="d0e376"></a>The
Correctness vs. Efficiency Problem</h2>
</div>
<p>Programmers working with <span class="emphasis"><em>E.
Vulgaris</em></span> must remember to store the iterator returned
when a callback is attached and pass it back to the event when the
callback is disconnected. This is tedious and it is tempting to
leave the callback attached &quot;for ever&quot; to avoid having to manage
the iterator. This usually leads to disaster and is always
frustrating for the hapless programmer.</p>
<p>The need to store the iterator can be removed by searching the
list of pointers before disconnecting the callback. However, in
<span class="emphasis"><em>E. Vulgaris</em></span> this technique
carries a significant performance penalty because the <tt class=
"classname">std::list&lt;&gt;</tt> it uses only supports search
algorithms with linear complexity. With <span class=
"emphasis"><em>E. Adaptabilis</em></span>, however, there is an
alternative. Specimen 8 provides a good example.</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;set&gt;
#include &quot;Event.hpp&quot;
using namespace std;
void log(int i) {
  clog &lt;&lt; &quot;void log(&quot; &lt;&lt; i &lt;&lt; &quot;)&quot; &lt;&lt; endl;
}

int main() {
  typedef std::set&lt;void (*)(int)&gt; container;
  Event&lt;int,container&gt; event;
  event.insert(log); // no need to store an
                     // iterator
  event.notify(8);
  event.erase(log); // efficient search and
                    // erase
  return 0;
}
</pre>
<p><span class="bold"><b>Specimen 8 - <span class="emphasis"><em>E.
Adaptabilis</em></span> using a <tt class=
"classname">std::set&lt;&gt;</tt></b></span></p>
<p>This variant uses a <tt class="classname">std::set&lt;&gt;</tt>
of function pointers as its container. The insertion, removal and
iteration operations are all &quot;fairly efficient&quot;. By that I mean
that, for most applications, efficiency is not an issue. And for
very demanding applications it is always possible to use a variant
of <span class="emphasis"><em>E. Adaptabilis</em></span> based on
specialised containers. It's even possible to use a specialised
iteration algorithm thanks to the public access of the nested
<tt class="classname">notify_function</tt> class.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e416" id="d0e416"></a>Summary and
Conclusion</h2>
</div>
<p>This paper has described a recently discovered species of Event
(Eventus Adaptabilis) with a remarkably wide range of habitats. E.
Adaptabilis is closely related to the more common Eventus Vulgaris
but is more adaptable in the following ways:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>It accepts callbacks taking parameters convertible to its own
argument type;</p>
</li>
<li>
<p>It accepts callbacks of ordinary function types or function
object types;</p>
</li>
<li>
<p>It can store built-in pointers or smart pointers to
callbacks;</p>
</li>
<li>
<p>It can use any of the standard containers and many other
container types;</p>
</li>
<li>
<p>It is immune to callbacks that disconnect themselves from the
event;</p>
</li>
<li>
<p>It allows user-defined iteration algorithms to be used.</p>
</li>
</ol>
</div>
<p>It achieves all this without sacrificing efficiency and without
forcing the programmer to store iterators. A rare specimen
indeed.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e442" id="d0e442"></a>References</h2>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] Gamma, Helm, Johnson and Vlissides,
<span class="citetitle"><i class="citetitle">Design Patterns,
Elements of Reusable Object-Oriented Software</i></span>,
Addison-Wesley, ISBN 0-201-63361-2.</p>
</div>
<div class="bibliomixed"><a name="Bass2002" id="Bass2002"></a>
<p class="bibliomixed">[Bass2002] Phil Bass, &quot;Implementing the
Observer Pattern in C++ - Part 1&quot;, <span class=
"citetitle"><i class="citetitle">Overload 52</i></span>, December
2002.</p>
</div>
<div class="bibliomixed"><a name="Bass2003" id="Bass2003"></a>
<p class="bibliomixed">[Bass2003] Phil Bass, &quot;Implementing the
Observer Pattern in C++ - Part 2&quot;, <span class=
"citetitle"><i class="citetitle">Overload 53</i></span>, February
2003.</p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e47" href="#d0e47" id=
"ftn.d0e47">1</a>]</sup> The <tt class="literal">std::</tt> prefix
has been omitted to improve the layout on the printed page.</p>
</div>
</div></p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
