    <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  :: Experiences of Implementing the Observer Design Pattern
(Part 3)</title>
        <link>https://members.accu.org/index.php/articles/464</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>




<div class="xar-mod-head"><span class="xar-mod-title">Design of applications and programs + Overload Journal #41 - Feb 2001</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/articles/">All</a>

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c67/">Design</a>
<br />

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c163/">41</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c67-163/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c67+163/">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;Experiences of Implementing the Observer Design Pattern
(Part 3)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 February 2001 16:46:05 +00:00 or Mon, 26 February 2001 16:46:05 +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>In the previous two columns of this 'accidental' series
[<a href="#Goodliffe1">Goodliffe1</a>] [<a href=
"#Goodliffe2">Goodliffe2</a>] I presented a number of
implementations of the Observer design pattern [<a href=
"#Gamma-">Gamma-</a>] in C++. The Observer pattern allows an object
(which we will call the <tt class="classname">Notifier</tt>) to
multicast events to other interested objects (the <tt class=
"classname">Listeners</tt>). These interested objects can register
or revoke their interest at run time.</p>
<p>Following the prior two articles I have devised a far superior
implementation. This implementation is:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>type safe,</p>
</li>
<li>
<p>flexible,</p>
</li>
<li>
<p>efficient,</p>
</li>
<li>
<p>generic,</p>
</li>
<li>
<p>safe (this is one of the important features here),</p>
</li>
<li>
<p>allows any number of callbacks per interface,</p>
</li>
<li>
<p>allows any number of parameters per callback,</p>
</li>
<li>
<p>comes very close to the original design goal I had in mind: the
Java listener interface idiom.</p>
</li>
</ul>
</div>
<p>It also uses some advanced C++ idioms that will be interesting
for the less experienced C++ programmer to learn about. It is a
neat, elegant piece of code. Remember that my application of the
Observer pattern is as part of the public API of a C++ library,
this motivates some of my design decisions.</p>
<p>I guess that these three articles have been a diary of my voyage
of discovery. However, this does not mean that this third
instalment necessarily represents the pinnacle of Observer pattern
implementation. In the previous articles we have covered some
interesting ground, and discovered some of the pitfalls of
implementation. Furthermore, some of those implementations may be
more appropriate to particular situations than this one.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e68" id="d0e68"></a>Other
approaches</h2>
</div>
<p>Before I present the implementation, it would be a good idea to
get an overview of what other observer implementations exist and
are used in the big wide world. This selection will be by no means
complete. For each of the items below I urge you to follow the
reference and read the article/documentation. Each of them uses C++
in a deep and clever way to present a useful and simple Observer
pattern framework.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e73" id="d0e73"></a>Troll Tech's Qt
signals/slots [<a href="#Qt">Qt</a>]</h3>
</div>
<p>This is a novel approach, based on 'signals' (messages) and
'slots' (message destinations). Qt is a very neat GUI library that
works on Unix and Win32. The KDE desktop environment is based upon
it. I have a lot of respect for their approach. It is very
flexible, type safe and certainly inventive. However, it has a
number of drawbacks which make it impractical for my use. First, it
would necessitate a dependency on a GUI library (which is far too
large a dependency for small code libraries). Second, it requires
the generation of some implementation code for each class using
signals or slots. This 'meta class' code will enlarge the code
base<sup>[<a name="d0e81" href="#ftn.d0e81" id=
"d0e81">1</a>]</sup>. Thirdly, as a consequence of this a meta
compilation stage is required to automatically generate this
code.</p>
<p>The Qt approach adds extensions to the C++ language (i.e. the
signal and slot keywords) to provide a very flexible
implementation. However, I am looking to stay strictly within the
bounds of standard C++<sup>[<a name="d0e87" href="#ftn.d0e87" id=
"d0e87">2</a>]</sup>.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e91" id="d0e91"></a>Rich Hickey
article &quot;Callbacks in C++ Using Template Functors&quot; in C++ Report
[<a href="#Hickey">Hickey</a>]</h3>
</div>
<p>Hickey has some strong views on what a callback is/should be,
some of which I am not sure I agree with. He reviews some of the
approaches and describes their shortfalls (interestingly, he slates
a simplistic version of what I present below). However, he presents
a novel method of using templates to create a type-safe and generic
callback system. However, as presented in the article the system is
not as flexible as we would like. For example, multiple numbers of
callbacks can be stored in a vector and iterated over. However, for
each notifying object you have to write attach/detach/iteration
code from scratch.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e99" id="d0e99"></a>Mark Bartosik
article &quot;Encapsulating the Observer Pattern&quot; in C/C++ Users Journal
[<a href="#Bartosik">Bartosik</a>]</h3>
</div>
<p>Now this is a really nice solution. I will not say too much
about it because my implementation is based heavily on Bartosik's
work. I include him in this list because I do not deserve credit
for what he has already done. Although based on Bartosik's design,
this implementation augments his work in several key areas.</p>
<p>I have to say that I was surprised that hardly anyone replied to
my calls for other Observer implementations in previous articles.
Either people do not have any better implementations (I find that
hard to believe), did not read the article (my heart sinks) or
could not be bothered (in which case, I now encourage you again to
respond - you do not have to write an article, just mail me your
code). If you know of any other good implementations provided by
off-the-shelf libraries, then please write in to let us know.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e109" id="d0e109"></a>The ideal
solution</h2>
</div>
<p>Perhaps the first question we should ask ourselves when
designing an implementation of the Observer design pattern is what
would we like it to look like? The ideal system would:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Be type safe</p>
</li>
<li>
<p>Be really easy to use</p>
</li>
<li>
<p>Be efficient (in terms of both time and space)</p>
</li>
<li>
<p>Does not involve inheritance; this would reduce the coupling in
class designs. This requirement could perhaps be relaxed to the
extent that listeners should not inherit from a base class, but
notifiers may.</p>
</li>
<li>
<p>Allows messages to be passed around with any number of
parameters - again in a type safe manner. (Qt allows you to have a
listener that does not use every single parameter of a message, but
this would be a nice feature, not a requirement; perhaps we could
write adaptors).</p>
</li>
<li>
<p>Can connect an event to anything (e.g. a function or member
function).</p>
</li>
<li>
<p>Can cope with listener objects being deleted safely; events will
not be sent to 'nothing' via a dangling object reference - this
only leads to curious core dumps.</p>
</li>
<li>
<p>Similarly, can cope with notifying objects being deleted.</p>
</li>
<li>
<p>Each notifier can send any number of different events (out of a
set fixed at compile time).</p>
</li>
<li>
<p>A listener can listen to any number of notifiers, and can
register and revoke an interest dynamically, not just at
construction/destruction.</p>
</li>
<li>
<p>Can filter out events that are of no interest to the listener
(of course, this could be done by the listener if needs be).</p>
</li>
</ul>
</div>
<p>This list has been compiled from my requirements and those of
the other systems described above. Now, I will admit at this stage
that we are not going to be able to provide all of these features.
However, we will get pretty close.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e150" id="d0e150"></a>What's
<span class="emphasis"><em>really</em></span> wrong with my
previous efforts [<a href="#Goodliffe1">Goodliffe1</a>] [<a href=
"#Goodliffe2">Goodliffe2</a>]?</h3>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Complex to use and not entirely intuitive</p>
</li>
<li>
<p>Dual inheritance hierarchy</p>
</li>
<li>
<p>No parameters in events, and only one type of event per
Notifier</p>
</li>
<li>
<p>Requires casting = not type safe</p>
</li>
</ul>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e175" id="d0e175"></a>What's wrong
with Qt?</h3>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The meta compiler and code bloat</p>
</li>
<li>
<p>All objects have to inherit from a base <tt class=
"classname">QObject</tt></p>
</li>
</ul>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e187" id="d0e187"></a>What's wrong
with Rich Hickey's?</h3>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Cannot cope with a destination or source object being
deleted</p>
</li>
<li>
<p>Cannot have a type with several different notification types
conveniently</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e197" id="d0e197"></a>Design
10</h2>
</div>
<p>Now we have a good understanding of the problem space, let us
see the new implementation. I have deliberately laboured this
background information so that when the implementation is presented
the reader can see exactly what problems are solved, and therefore
why it is so neat.</p>
<p>This approach is based on Bartosik's implementation [<a href=
"#Bartosik">Bartosik</a>]. What I chiefly add to his work is object
safety: the ability to safely delete either a <tt class=
"classname">Notifer</tt> or a <tt class="classname">Listener</tt>
without your program crashing at some random point in the future
when a dangling pointer is dereferenced. I also remove some
complications to the core implementation that he provides. These
are discussed in the <span class="bold"><b>Extensions</b></span>
section later.</p>
<p>First I will describe how to use the framework, then we will see
how it is implemented. This is presentation in order of increasing
complexity!</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e218" id="d0e218"></a>How to use the
framework</h3>
</div>
<p>The use of this notifier framework is simple. Using the good old
examples of the <tt class="classname">Exhibitionist</tt> and
<tt class="classname">Voyeur</tt> classes (which are types of
<tt class="classname">Notifier</tt> and <tt class=
"classname">Listener</tt>, respectively) we would write something
like the following. First we forward declare the class that will be
sending the events.</p>
<pre class="programlisting">
class Exhibitionist;
</pre>
<p>Next we define an interface for this class to call back to. This
interface defines the events that the <tt class=
"classname">Exhibitionist</tt> can send. Note that we must include
a <tt class="literal">typedef</tt> describing the type of the
<tt class="classname">Notifier</tt> class. This is needed by the
implementation of the framework later on. In this example we have
only one event. Note that I prefix its name with <tt class=
"classname">Exhibitionist_</tt>. I have found this to be a useful
convention, use it at your discretion.</p>
<pre class="programlisting">
class ExhibitionistListener {
  public:
    typedef Exhibitionist notifier_type;
    virtual void Exhibitionist_Event (Exhibitionist *src, int data) {}
};
</pre>
<p>Note that the callback methods are required to be virtual (the
system will not work otherwise), and that the method provides a
default implementation that does nothing. You could define the
method as pure virtual (i.e. write &quot;= 0;&quot; rather than &quot;{}&quot;). Like
this, however, you can chose to only handle some events and do
nothing for others by being selective in your overriding.</p>
<p>Now that the interface is defined we can implement a <tt class=
"classname">Voyeur</tt> class in terms of it. This is shown below.
Note that the <tt class="classname">Voyeur</tt> inherits from
<tt class="classname">Listener&lt;ExhibitionistListener&gt;</tt>.
This class inherits from the <tt class=
"classname">ExhibitionistListener</tt> directly. Therefore the
<tt class="classname">Voyeur</tt> can redefine the interface's
virtual methods to act on any notifications.</p>
<pre class="programlisting">
class Voyeur : public Listener&lt;ExhibitionistListener&gt; {
  public:
    void foo(Exhibitionist *e) {
// we want to listen to the Exhibitionist
      attachTo(e);
    }
    virtual void Exhibitionist_Event (Exhibitionist *src, int data) {
      cout &lt;&lt; &quot;Moo &quot; &lt;&lt; data &lt;&lt; '\n';
    }
};
</pre>
<p>If you call <tt class="methodname">Voyeur::foo</tt> the
<tt class="classname">Voyeur</tt> will attach itself to the
specified <tt class="classname">Exhibitionist</tt>. Whenever this
<tt class="classname">Exhibitionist</tt> raises an <tt class=
"classname">Exhibitionist_Event</tt> then the <tt class=
"classname">Voyeur</tt> object will receive the event and
<tt class="classname">moo</tt> accordingly. The <tt class=
"classname">Voyeur</tt> can explicitly disconnect itself from an
<tt class="classname">Exhibitionist</tt> by calling a <tt class=
"methodname">detachFrom(Exhibitionist *)</tt> method.</p>
<p>So finally it remains for us to see how to implement an
Exhibitionist. Again, it is simple.</p>
<pre class="programlisting">
class Exhibitionist : public Notifier&lt;ExhibitionistListener&gt; {
  public:
    doSomething(){
      notify( &amp;ExhibitionistListener::Exhibitionist_Event, 10);
    }
};
</pre>
<p>That is it! Now if you call <tt class=
"methodname">Exhibitionist::doSomething</tt> it will send an event
to all attached listeners.</p>
<p>You will note that in the notification we only specify one
integer parameter (as well as the actual callback method), although
the interface method had two parameters. The framework
automatically provides the first parameter as a pointer to the
source object. This means that when you define an interface you
have to bear this in mind.</p>
<p>Why have I done this? I have found that it is generally useful
to know which the source object is when handling a notification.
This is especially useful when you are listening to more than one
object of the same type. Perhaps this is specific to my application
of the pattern (somehow I doubt this).</p>
<p>Although I have not shown it here, the system provides a
mechanism for <tt class="classname">Listener</tt>s to be
automatically informed of when <tt class="classname">Notifier</tt>s
are deleted which is often very useful. However, the real bonus of
the whole system is this: if either of the <tt class=
"classname">Voyeur</tt> or <tt class="classname">Exhibitionist</tt>
objects are deleted, the link between them is automatically broken
(we will see how later). This is what makes the system <span class=
"emphasis"><em>simple</em></span> and <span class=
"emphasis"><em>safe</em></span> to use.</p>
<p>Just in case you find it hard to visualise, the hierarchy of
classes involved looks something like this (although the <tt class=
"classname">Listener&lt;&gt;</tt> is in fact inheriting from
<tt class="classname">ExhibitionistListener</tt>).</p>
<div class="figure"><a name="d0e347" id="d0e347"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/observer%20design%20pattern%20figure%201.png" align=
"middle"></div>
<p class="title c3">Figure 1. </p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e352" id=
"d0e352"></a>Strengths/Drawbacks</h3>
</div>
<p>As you can see, a system of this type is generic (not limited to
a few interface types) type safe (parameter types are preserved and
C++ conversions can be employed), flexible (allows any number of
event types each with any number of parameters, modulo the implicit
<tt class="varname">src</tt> pointer), and above all really easy to
use (partly due to the safety features provided).</p>
<p>The only major wish-list features we have not provided are the
ability to call non-member functions (we can create adaptors to do
this) and the freedom from inheritance. However, this latter ideal
is not really attainable since you need to inherit from a base
class to gain the notification implementation.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e362" id="d0e362"></a>How the
framework is implemented</h3>
</div>
<p>Since using the <tt class="classname">Notifier</tt> and
<tt class="classname">Listener</tt> classes is deceptively simple
there has to be some hairy code making it work in the background.
This is where it gets interesting.</p>
<p>In order to show the full implementation we will add
functionality a step at a time. The full versions of the <tt class=
"classname">Notifier</tt> and <tt class="classname">Listener</tt>
classes are heavily interdependent in order to implement the safety
features. I have ordered some of the following code to aid the
reader. You should (hopefully) be able to read from the top
down.</p>
<p>The <tt class="classname">Notifier</tt> implementation looks
roughly like this:</p>
<pre class="programlisting">
template &lt;class interface_type&gt; Listener;
template &lt;class interface_type&gt;
class Notifier {
  public:
    typedef Listener&lt;interface_type&gt; listener_type;
    friend listener_type;
  private:
    std::vector&lt;listener_type*&gt; listeners;
  protected:
    template &lt;typename func_type&gt;
    void notify(func_type func);
    template &lt;typename func_type, typename p1_type&gt;
    void notify(func_type func, const p1_type &amp;p1);
    template &lt;typename func_type, typename p1_type, typename p2_type&gt;
    void notify(func_type func, const p1_type &amp;p1, const p2_type &amp;p2);
    virtual ~Notifier();
  private:
// only called by listener_type, returns whether call is valid
    bool attach(listener_type *listener){
      if(find(listeners.begin(), listeners.end(), listener) != listeners.end())
          return false;
      listeners.push_back(listener);
      return true; 
    }
    bool detach(listener_type *listener) {
      if (find(listeners.begin(), listeners.end(), listener)== listeners.end())
         return false;
      listeners.erase(listener);
      return true;
    }
    typedef Notifier&lt;interface_type&gt; self_type;
    typedef typename interface_type::notifier_type c_notifier_type;
    Notifier(const self_type &amp;);
    self_type &amp;operator=(const self_type &amp;);
    void doEvent(const AbstractEvent&lt;interface_type&gt;&amp;);
};
</pre>
<p>What we have seen above is basically the management of a list of
<tt class="classname">Listener</tt> objects. The other interesting
point that can be seen is that we have declared a version of the
<tt class="classname">notify</tt> method for each number of
parameters which we want to support. This is a running theme
through the implementation. In the code above we can handle
notifications with 0-2 parameters. You can extend the
implementation as required<sup>[<a name="d0e396" href="#ftn.d0e396"
id="d0e396">3</a>]</sup>. Note that the notify functions are
template members. This allows us to provide callback methods with
any type of parameters in a type safe way.</p>
<p>Note that the <tt class="literal">c_notifier_type typedef</tt>
describes the concrete <tt class="classname">Notifier</tt> type
that will inherit from this class. We need this in the
implementation later on.</p>
<p>Now to implement the <tt class="methodname">notify</tt> methods,
we define a template functor (in a similar vein to [<a href=
"#Hickey">Hickey</a>]) to call the appropriate method on the
<tt class="classname">interface_type</tt>. We define a simple
abstract interface for this functor:</p>
<pre class="programlisting">
template &lt;class interface_type&gt;
class AbstractEvent {
  public:
    virtual void operator()(interface_type *listener) const = 0;
};
</pre>
<p>Now we add a <tt class="methodname">doEvent</tt> method to the
<tt class="classname">Notifier</tt> class interface that iterates
over every attached <tt class="classname">Listener</tt> and invokes
the functor on it. This is called by each of the notify
methods.</p>
<pre class="programlisting">
void doEvent(const AbstractEvent&lt;interface_type&gt; &amp;event){
  for (size_t i = 0; i &lt; listeners.size(); i++) {
    event(listeners[i]);
  }
}
</pre>
<p>It is the Event class (that inherits from the <tt class=
"classname">AbstractEvent</tt>) that does the clever stuff -
calling the appropriate interface method. Before showing the class
let us see how the notify methods create <tt class=
"classname">Event</tt> objects. This shows the case of one extra
parameter, extend or contract accordingly for the others:</p>
<pre class="programlisting">
template &lt;typename func_type, typename p1_type&gt;
void Notifier::notify(func_type func, const p1_type &amp;p1){
  typedef Event&lt;interface_type, func_type, c_notifier_type, p1_type&gt; event_type;
  doEvent(event_type(func, static_cast&lt;c_notifier_type*&gt;(this), p1));
}
</pre>
<p>Although this does not mean much on its own, it will be helpful
to bear in mind as you read the definition of the <tt class=
"classname">Event</tt> class. Again it is declared for 0-2
parameters and may be extended accordingly. The definition of
<tt class="varname">arg_count</tt> and <tt class=
"varname">num_type</tt> follow, with a discussion of the code.</p>
<pre class="programlisting">
template &lt;class interface_type, typename listener_func,typename p1_type = def_type,
          typename p2_type = def_type&gt;
class Event : public AbstractEvent&lt;interface_type&gt; {
  public:
    explicit Event(listener_func func, const p1_type &amp;p1 = p1_type(),
                   const p2_type &amp;p2 = p2_type())
       : func(func), p1(p1), p2(p2), {}
    virtual void operator()(interface_type *listener) const {
      const unsigned int argCount = arg_count&lt;p1_type&gt;::count
                                  + arg_count&lt;p2_type&gt;::count;
      if (listener) invokeImpl(listener, num_type&lt;argCount&gt;());
    }
  protected:
    template &lt;class T&gt;
    void invokeImpl(T *listener, num_type&lt;0&gt;) const {(void)(listener-&gt;*func)(); }
    template &lt;class T&gt;
    void invokeImpl(T *listener, num_type&lt;1&gt;) const {(void)(listener-&gt;*func)(p1); }
    template &lt;class T&gt;
    void invokeImpl(T *listener, num_type&lt;2&gt;) const {(void)(listener-&gt;*func)(p1, p2);
    }
  private:
    const listener_func func;
    const p1_type       p1;
    const p2_type       p2;
};
</pre>
<p>The constructor stores the callback method to call and the
parameters with which to call it. If you do not instantiate the
template class with all the parameter types then a <tt class=
"classname">def_type</tt> is supplied. This is a dummy type that
represents 'not used'. It looks like this:</p>
<pre class="programlisting">
  class def_type {};
</pre>
<p>It is the <tt class="methodname">operator()</tt> method that
works out how many parameter types have been supplied, by using the
<tt class="classname">arg_count</tt> class - this works out how
many of the template parameters were explicitly specified (the
others will be <tt class="classname">def_type</tt>). <tt class=
"classname">arg_count</tt> looks like this:</p>
<pre class="programlisting">
  template &lt;typename T&gt; struct arg_count { enum { count=1 }; };
  template &lt;&gt; struct arg_count&lt;def_type&gt; { enum { count=0 }; };
</pre>
<p>You may like to look at that a little more just to work out how
the <tt class="classname">argCount</tt> variable gets to hold the
number of <i class="parameter"><tt>func_type</tt></i> parameters
that have been specified.</p>
<p>Using this value, <tt class="methodname">operator()</tt> selects
one of the overloaded <tt class="methodname">invokeImpl</tt>
methods to call. There is one of these for each of the number of
parameters supported (0-2). We use another clever template 'macro'
<tt class="classname">num_type</tt> to select only the relevant
<tt class="methodname">invokeImpl</tt>. The <tt class=
"methodname">invokeImpl</tt>s are template member functions when
they need not be (after all the T type is already known to be
<tt class="classname">interface_type</tt>). This is vital though,
since only one of these methods will be valid for each event. The
other <tt class="methodname">invokeImpl</tt>s are ignored by the
compiler.</p>
<p><tt class="classname">num_type</tt> is provided by the following
innocuous bit of code:</p>
<pre class="programlisting">
  template&lt;unsigned&gt; class num_type {};
</pre>
<p>Now, each <tt class="methodname">invokeImpl</tt> method calls
the appropriate <tt class="classname">interface_type</tt> member
function with the appropriate number of parameters.</p>
<p>Now we have seen the entire trace of execution of a <tt class=
"classname">Notifier</tt> callback. It quite cunning, and perhaps
you will need to read it over a couple of times to really
appreciate what is going on (I certainly did to check I wrote it
correctly!)</p>
<p>The best bit about all these template shenanigans is that it is
all worked out at compile time - it has very little runtime
overhead at all (the expense is a little auto-generated code, which
has a very small practical cost).</p>
<p>Now let us see what the <tt class="classname">Listener</tt>
looks like. (Do not worry, the frightening bit is over now.) The
<tt class="classname">Listener</tt> obviously provides a mechanism
to attach to and detach from <tt class="classname">Notifier</tt>s.
It also remembers which <tt class="classname">Notifier</tt>s it is
attached to, so that it can detach from them if it is deleted.</p>
<pre class="programlisting">
template &lt;class interface_type&gt;
class Listener : public interface_type {
  public:
    typedef Notifier&lt;interface_type&gt; notifier_type;
    typedef typename interface_type::notifier_type c_notifier_type;
    friend notifier_type;
  private:
    std::vector&lt;notifier_type*&gt; notifiers;
  public:
// Now whether attachTo and detachFrom are public or protected is your choice, it 
// depends on how you want to use the API
    void attachTo(notifier_type *notifier) {
      if (notifier-&gt;attach(this))notifiers.push_back(notifier);
    }
    void detachFrom(notifier_type *notifier) {
      if (notifiers.erase(notifier)) notifier-&gt;detach(this);
    }
  protected:
    virtual ~Listener() {
// This provides some of the 'object safety'
      for (size_t i = 0; i &lt; notifiers.size(); i++) { notifiers[i]-&gt;detach(this); }
    }
  private:
    typedef Listener&lt;interface_type&gt; self_type;
    Listener(const self_type &amp;);
    self_type &amp;operator=(const self_type &amp;);
};
</pre>
<p>That is not really too hair raising. There is one member
function that I have left out, which I now present. This is the
mechanism by which a <tt class="classname">Listener</tt> can be
automatically informed when a <tt class="classname">Notifier</tt>
is deleted.</p>
<p>The <tt class="classname">Listener</tt> declares a protected
method using the <tt class="classname">c_notifier_type
typedef:</tt></p>
<pre class="programlisting">
  virtual void Notifier_Deleted(c_notifier_type *notifier) {}
</pre>
<p>This can be reimplemented by concrete <tt class=
"classname">Listener</tt> classes (for example, the <tt class=
"classname">Voyeur</tt> class) if they want to know when their
<tt class="classname">Notifier</tt> is deleted. The <tt class=
"classname">Voyeur</tt> would override <tt class=
"methodname">Notifier_Deleted(Exhibitionist *src),</tt> for
example.</p>
<p>This is called by a private <tt class="classname">Listener</tt>
method, which is in turn called by the <tt class=
"classname">Notifier</tt> destructor. This is why the <tt class=
"classname">notifier_type</tt> is a <tt class="literal">friend</tt>
of the <tt class="classname">Listener</tt> class. Here is the final
<tt class="literal">private</tt> <tt class=
"classname">Listener</tt> method:</p>
<pre class="programlisting">
  void NotifierImpl_Deleted(c_notifier_type *src) {
    notifiers.erase(static_cast&lt;notifier_type*&gt;(src));
    this-&gt;Notifier_Deleted(src);
  }
</pre>
<p>Finally, we see how the <tt class="classname">Notifier</tt>
destructor calls this:</p>
<pre class="programlisting">
template &lt;interface_type&gt;
virtual Notifier::~Notifier(){
  for (size_t i = 0; i &lt; listeners.size(); i++){
    listeners[i]-&gt;NotifierImpl_Deleted(static_cast&lt;c_notifier_type*&gt;(this));
  }
}
</pre>
<p>This completes the description of the implementation of the
Observer pattern. It involves some fairly complex C++ code, so you
may want to go over it again. Whilst it is a lot to take in, it is
in fact a really elegant and neat solution. The <span class=
"bold"><b>Getting the Code</b></span> section at the end of this
article describes where you can download the complete
implementation. You may find this useful.</p>
<p>Note that in my 'real' version the implementation classes
(<tt class="classname">Event</tt>, <tt class=
"classname">def_type</tt> et al) which clutter the global namespace
unnecessarily have been hidden (slightly) within an <tt class=
"literal">Impl namespace</tt>. This prevents the user from becoming
unnecessarily caught up in the implementation details. It also
contains another slight modification, described in the next
section.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e630" id="d0e630"></a>Tailoring it
to the real world</h2>
</div>
<p>Now that is such a neat solution there must surely be a
drawback.</p>
<p>When I first started using this implementation in the TSE3
library [<a href="#Goodliffe3">Goodliffe3</a>] in place of the
earlier version presented in the previous article [<a href=
"#Goodliffe2">Goodliffe2</a>] I was somewhat shocked to see how
much my code grew by. We all know the old adages about templates
leading to code bloat, however, such large file size increases were
pretty hard to comprehend.</p>
<div class="table"><a name="d0e643" id="d0e643"></a>
<table summary="" border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;tbody&gt;
<tr>
<td>TSE3 library prior to new implementation</td>
<td>~ 5 Mb</td>
</tr>
<tr>
<td>TSE3 library after new implementation</td>
<td>~ 16 Mb</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c3">Table 1. </p>
</div>
<p>If this was the consequence of using this new approach then it
could simply not be justified.</p>
<p>So I began an investigation into what was going on. When
compiling small stand-alone programs I could not find a significant
difference in file size, and it was this that lead me to discover
what the real problem was.</p>
<p>The TSE3 library is built under Linux as a set of shared
libraries (using gcc 2.95.2). Each of these shared libraries
exports a table of symbol names (i.e. function, class and variable
names) that is used to dynamically link a program against it. Small
test programs do not have such a table of information.</p>
<p>The small test programs were optimised by the compiler so that
all the template tomfoolery shown above was reduced to a few basic
instructions. However, despite these optimisations also being
performed for the library code, each version of the <tt class=
"classname">Notifier</tt> and <tt class="classname">Listener</tt>
class (i.e. each class which derives from them - in TSE3 there are
a lot of these) introduced a bunch of new names into the external
linkage table.</p>
<p>The problem names did not come from the Observer implementation,
though. They came from our dearly loved standard C++ library. At
first I was using <tt class="classname">std::set</tt> rather than
<tt class="classname">std::vector</tt> and many, many names of
instantiated <tt class="classname">std::set</tt>s were polluting
the symbol table. Since STL containers have a number of template
parameters (themselves templates), the single mention of a set of a
<tt class="classname">Notifier</tt> type which is also itself a
template type leads to a name which is easily around 300 characters
long. I experimented with some different STL containers to see what
difference was made:</p>
<div class="table"><a name="d0e685" id="d0e685"></a>
<table summary="" border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;tbody&gt;
<tr>
<td>std::set</td>
<td>~ 16 Mb</td>
</tr>
<tr>
<td>std::vector</td>
<td>~ 8.2 Mb</td>
</tr>
<tr>
<td>std::list</td>
<td>~ 8.9 Mb</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c3">Table 2. </p>
</div>
<p>So having found the problem it seemed pretty hard to avoid. I
have found a solution. However, it is quite embarrassing. Welcome
to Pete's minimalist template-free, type-free container class. Yes,
I cast all pointers to <tt class="type">void*</tt>!</p>
<pre class="programlisting">
class void_list {
  public:
    void_list();
    ~void_list();
    bool push_back(void *p); // no insertion of duplicate entries
    bool erase(void *p);
    unsigned int size();
    void *operator[](unsigned int index);
  private:
    class impl;
    impl *pimpl;
};
</pre>
<p>The <tt class="classname">void_list</tt> implementation is
hidden behind a <i class="firstterm">Pimpl</i> class [<a href=
"#Sutter">Sutter</a>], and this implementation is in terms of a
<tt class="classname">std::vector.</tt> I leave the implementation
(basic as it is) as an exercise for the reader.</p>
<p>Using this <tt class="classname">void_list</tt> in the
<tt class="classname">Notifier</tt> and <tt class=
"classname">Listener</tt> classes (with appropriate casts) brought
the library size down dramatically. Note that since the library
code is doing the casting, not the user, and since the code has
been carefully checked to be correct, the implementation can still
be reasonably called 'type-safe'.</p>
<div class="table"><a name="d0e736" id="d0e736"></a>
<table summary="" border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;tbody&gt;
<tr>
<td>void_list</td>
<td>~ 5 Mb</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c3">Table 3. </p>
</div>
<p>Having used this framework heavily for over three months now,
there are a number of other experiences which should be noted.</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>If you call a notify with wrong parameters, the compiler errors
can be somewhat cryptic, steeped in reams of template language,
only to be interpreted by the bold of heart. Maybe new compiler
technology will fix this.</p>
</li>
<li>
<p>Being a multiple Notifier involves some syntax overhead. With
the version of gcc I am using (2.95.2) not specifying which notify
causes the compiler to bomb completely. It can be worked around by
specifying an explicit function (e.g. <tt class=
"methodname">Notifier&lt;ExhibitionistListener&gt;::notify(...)</tt>
). I am not sure whether the compiler should actually be able to
deduce the correct member function, but I am pretty sure it should.
I need a language lawyer to tell me.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e757" id=
"d0e757"></a>Extensions</h2>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>One possible extension to this system is providing a delayed
callback when the <tt class="methodname">notify</tt> method is
called. This may avoid some re-entrancy problems and reduce
overhead in some cases, for example in the case where an event
handler may itself cause several other notifications to be raised.
It may also prevent infinite looping if only one notification is
buffered at a time. It also, however, imposes some overhead (OS
timer events have to be set up) - this may be OK for GUI updates,
maybe not so good for other more real-time notifications.</p>
</li>
<li>
<p>With multiple threads accessing the <tt class=
"classname">Notifier</tt> and Listener objects, some locking is
required to ensure correct operation.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e773" id=
"d0e773"></a>Conclusions</h2>
</div>
<p>In the previous article I suggested that it is impossible to
construct the perfect Observer pattern implementation. The version
presented here is certainly much better than my previous efforts,
however at a cost (mainly a slight growth in code size).</p>
<p>Which kind of implementation of the Observer design pattern you
use will largely depend on your needs. Different implementations
are tailored to different circumstances, and need varying degrees
of trade-off between factors such as speed, type safety,
simplicity, public visibility, and code size.</p>
<p>I hope that this article has been useful, and once again invite
people to respond with their 'killer' Observer pattern
implementations. This time I promise that I shall try not to write
a forth article in the series. We will see...</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e782" id="d0e782"></a>Getting the
code</h2>
</div>
<p>The implementation code for this article is available as a part
of the TSE3 library, available from http://TSE3.sourceforge.net.
Get the 0.0.18 version for the code to match this
article<sup>[<a name="d0e787" href="#ftn.d0e787" id=
"d0e787">4</a>]</sup>. See the file src/tse3/Notifier.h in the
source archive for the implementation. There is online
documentation for the <tt class="classname">Notifier</tt> class
at</p>
<p><a href=
"http://TSE3.sourceforge.net/doc/api/TSE3__Notifier.html" target=
"_top">http://TSE3.sourceforge.net/doc/api/TSE3__Notifier.html</a>.</p>
<p>The library also shows some heavy duty use of the mechanism to
prove it really works.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e800" id="d0e800"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Goodliffe1" id="Goodliffe1"></a>
<p class="bibliomixed">[Goodliffe1] Pete Goodliffe. Experiences of
Implementing the Observer Design Pattern (Part 1). In: <span class=
"citetitle"><i class="citetitle">Overload 37</i></span>, 2000.</p>
</div>
<div class="bibliomixed"><a name="Goodliffe2" id="Goodliffe2"></a>
<p class="bibliomixed">[Goodliffe2] Pete Goodliffe. Experiences of
Implementing the Observer Design Pattern (Part 2). In: <span class=
"citetitle"><i class="citetitle">Overload 38</i></span>, 2000.</p>
</div>
<div class="bibliomixed"><a name="Gamma-" id="Gamma-"></a>
<p class="bibliomixed">[Gamma-] Gamma, Helm, Johnson, Vlissades.
<span class="citetitle"><i class="citetitle">Design Patterns -
Elements of Reusable Object-Oriented Software</i></span>.
Addison-Wesley, 1995. ISBN: 0201633612.</p>
</div>
<div class="bibliomixed"><a name="Qt" id="Qt"></a>
<p class="bibliomixed">[Qt] Trolltech. The Qt Library. <span class=
"bibliomisc"><a href="http://www.trolltech.com" target=
"_top">http://www.trolltech.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Hickey" id="Hickey"></a>
<p class="bibliomixed">[Hickey] Rich Hickey. Callbacks in C++ Using
Template Functors. 1994. In: <span class="citetitle"><i class=
"citetitle">C++ Report</i></span>, February 1995. Available from:
<span class="bibliomisc"><a href=
"http://www.bestweb.net/~rhickey/functor.html" target=
"_top">http://www.bestweb.net/~rhickey/functor.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Bartosik" id="Bartosik"></a>
<p class="bibliomixed">[Bartosik] Mark Bartosik. Encapsulating the
Observer Pattern. In: <span class="citetitle"><i class=
"citetitle">C/C++ Users Journal</i></span>, October 1998. Available
from: <span class="bibliomisc"><a href=
"http://www.cuj.com/archive/1610/feature.html" target=
"_top">http://www.cuj.com/archive/1610/feature.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Goodliffe3" id="Goodliffe3"></a>
<p class="bibliomixed">[Goodliffe3] Pete Goodliffe. Trax Sequencer
Engine Version 3. Available from: <span class="bibliomisc"><a href=
"http://TSE3.sourceforge.net/" target=
"_top">http://TSE3.sourceforge.net/</a></span></p>
</div>
<div class="bibliomixed"><a name="Sutter" id="Sutter"></a>
<p class="bibliomixed">[Sutter] Herb Sutter. Guru of the Week #24.
Available from: <span class="bibliomisc"><a href=
"http://www.peerdirect.com/Resources%20/gotw024.html" target=
"_top">http://www.peerdirect.com/Resources /gotw024.html</a></span>
(Also in: Herb Sutter. <span class="citetitle"><i class=
"citetitle">Exceptional C++</i></span>. Addison-Wesley, 2000. ISBN:
0-201-61562-2.)</p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c4" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e81" href="#d0e81" id=
"ftn.d0e81">1</a>]</sup> More so than the code generated in my
implementation.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e87" href="#d0e87" id=
"ftn.d0e87">2</a>]</sup> As an aside, however, I have used the Qt
library to implement a program that uses my library with the
Notifier framework. The two systems can be successfully used
alongside each other.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e396" href="#d0e396" id=
"ftn.d0e396">3</a>]</sup> In my real implementation I support 0-4
parameters. Any more and you begin to ask yourself whether the
callbacks are providing the right information.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e787" href="#d0e787" id=
"ftn.d0e787">4</a>]</sup> I have butchered the purity of the design
somewhat in later versions to slightly improve performance. These
modifications may be interesting for the reader to look at.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
