    <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 2)</title>
        <link>https://members.accu.org/index.php/journals/481</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 #38 - Jul 2000 + 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/c166/">38</a>
                    (6)
<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/c166-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c166+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;Experiences of Implementing the Observer Design Pattern
(Part 2)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 July 2000 17:50:57 +01:00 or Wed, 26 July 2000 17:50:57 +01: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>I had not originally intended to write a follow-up article to my
previous observer design pattern article [<a href=
"#Goodliffe">Goodliffe</a>]. However, four more months of
experience have given me further insights and augmented my
implementation of the design. My original article has accidentally
grown into a series of two articles, and even now I am convinced I
have not found all the answers. One of the things that I like about
being a programmer is that I am constantly learning.</p>
<p>Since the previous article described the observer design
pattern, I do not intend to cover that ground again - I will just
put in the obligatory reference to the GoF book [<a href=
"#GoF">GoF</a>] and move on.</p>
<p>In this article, as in the previous one, I present a number of
implementation approaches, and discuss their relative merits and
problems.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e32" id="d0e32"></a>Where we got to
last time</h2>
</div>
<p>In [<a href="#Goodliffe">Goodliffe</a>] I presented four
different approaches to an observer pattern implementation (which
worked with varying degrees of success). I favoured the penultimate
(slightly less safe) version. Four months later, do I still prefer
the less safe version?</p>
<p>When my code works, I do. I find the logic of calling <tt class=
"literal">notifer-&gt;attach</tt> more intuitive than calling
<tt class="literal">attach(notifier)</tt>. I also like to be made
to think about detaching from <tt class="classname">Notifier</tt>s
rather than blindly trusting that it will be done for me.</p>
<p>However, as I mentioned in [<a href="#Goodliffe">Goodliffe</a>],
debugging broken observer links is a nightmare, since it is pure
run-time stuff - the compiler will not catch any of our mistakes.
The debugger is your best friend in these situations. There have
been a number of times (when scratching my head) that I have been
tempted to move to the 'safety' model where this would be less
necessary.</p>
<p>Perhaps a good argument in favour of the safe version is the
particular use the pattern will be put to in my code. I am writing
a library. It provides the observer pattern as a means for the user
to monitor state changes, as well as using it internally. The 'less
safe but less overhead' pattern implementation therefore requires
the library user to be very careful about detaching from objects.
If the user gets something wrong, they will probably have an even
more confusing debugging session than I would.</p>
<p>The various implementation approaches that I present below are
based on the 'less safe' version, but will equally be applicable to
the 'safe' one. (Indeed, the extensions themselves add a degree of
safety).</p>
<p>The classes involved in the original implementation presented in
[<a href="#Goodliffe">Goodliffe</a>] are <tt class=
"classname">Notifier</tt> and <tt class="classname">Listener</tt>.
The <tt class="classname">Listener</tt> has only two methods that
are called when an observable event is raised, <tt class=
"methodname">updated</tt> and <tt class=
"methodname">deleted</tt>.</p>
<p>My dissatisfaction with the design I arrived at previously is
that I wanted Java-like listener interfaces, where a specific
listener method is called for each type of event. In the end I got
a single method being called for all updates, which is less
intuitive (to my mind, anyway).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e82" id="d0e82"></a>Something to
talk about</h2>
</div>
<p>The discussion in this article will be somewhat nebulous unless
we have something concrete to use as an example. So let us consider
a Book class<sup>[<a name="d0e87" href="#ftn.d0e87" id=
"d0e87">1</a>]</sup>. A Book contains a number of Chapters and a
Chapter contains a number of Pages. These classes sit in a
Notifier/Listener framework as shown below.</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/observer%20pattern%20pete%20goodliffe%201.png" align=
"middle"></div>
<p><tt class="classname">Book</tt> and <tt class=
"classname">Chapter</tt> are <tt class="classname">Listener</tt>s,
attached to their contents. <tt class="classname">Chapter</tt> and
<tt class="classname">Page</tt> are <tt class=
"classname">Notifier</tt>s, informing their <tt class=
"classname">Listener</tt>s when they are altered. For example, when
a <tt class="classname">Chapter</tt> gains a new page, it will send
an updated message to the <tt class="classname">Book</tt> it is in.
<tt class="classname">Chapter</tt> has the following updated reason
codes that the <tt class="classname">Book</tt> class uses to
maintain its table of contents:</p>
<pre class="programlisting">
enum ChapterReasonCodes {chapter_TitleAltered, chapter_NoPagesAltered };
</pre>
<p>I am sure that you could argue that this is either a sublime or
ridiculous set of classes. However, they are sufficient to give us
something concrete to talk about, so in my mind they are more than
perfectly formed.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e130" id="d0e130"></a>Design 5:
Adaptors</h2>
</div>
<p>Well, here is the good news. It is possible to get the Java-like
listener type of interface that I was looking for, but it will not
come for free.</p>
<p>By adding two new classes to our previous solution we can get
these Java-like listener interfaces. We add an 'adaptor'
class<sup>[<a name="d0e137" href="#ftn.d0e137" id=
"d0e137">2</a>]</sup> for each <tt class="classname">Notifier</tt>.
Where before <span class="emphasis"><em>our</em></span> class
inherited from <tt class="classname">Listener</tt>, it is now
<span class="emphasis"><em>the adaptor</em></span> class that
inherits from <tt class="classname">Listener</tt>. The adaptor's
<tt class="methodname">updated</tt> method switches on the reason
code (or aspect in GoF parlance) and sends it to a suitably named
method. To make life easier for us, this is implemented as an array
lookup.</p>
<p>We define the methods that will be called in the second class,
an abstract interface (mixin) class. This interface class is shown
below; it is what our <tt class="classname">Book</tt> class will
now inherit from.</p>
<pre class="programlisting">
class ChapterListenerInterface {
  public:
    virtual void ~ChapterListenerInterface() = 0;

// These methods are called when the Chapter Notifier sends an event

    virtual void chapter_titleAltered()     = 0;
    virtual void chapter_noPagesAltered()   = 0;
    virtual void chapter_deleted() = 0;

  private:

// Are you following this? Or just assuming it is correct?

    ChapterListenerInterface() {}
    ChapterListenerInterface(const ChapterListenerInterface &amp;);
    ChapterListenerInterface &amp;operator= (const ChapterListenerInterface &amp;);
};
</pre>
<p>Now we can define the adaptor class, ChapterListener, that
derives from the above abstract interface:</p>
<pre class="programlisting">
class ChapterListener : public Listener {
  public:
    ChapterListener(ChapterListenerInterface *if) : dest(if), src(0) {}
    ~ChapterListener() {if (src) src-&gt;detach(this); }

    void attachTo(Chapter *chapter) 
    {
      if (src) detach();
      src = chapter;
      src-&gt;attach(this);
    }
    
    virtual void updated(Notifier *source, int rc) 
    {
      switch (rc) {
        case chapter_TitleAltered:
          dest-&gt;chapter_titleAltered();
          break;
        case chapter_NoPagesAltered:
          dest-&gt;chapter_noPagesAltered();
          break;
      }
    }

    virtual void deleted(Notifier *source) 
    {
      src = 0;
      dest-&gt;chapter_deleted();
    }

  private:
    ChapterListenerInterface   *dest; // where to forward events
    Chapter                    *src;  // source of events
};
</pre>
<p>The <tt class="classname">Book</tt> class contains a <tt class=
"classname">ChapterListener</tt> adaptor object by value. This
ensures that the <tt class="classname">Book</tt> and its adaptor's
lifetimes are bound together. For example:</p>
<pre class="programlisting">
class Book : public ChapterListenerInterface
{
  public:
    Book()     : chapterListener(this){ chapterListener.attachTo(&amp;chapter);}
// Overriden versions of the ChapterListenerInterface methods

  private:
    Chapter     chapter; // say we only have one chapter ATM!
    ChapterListener chapterListener;
};
</pre>
<p>When the <tt class="classname">Book</tt> is deleted it will be
automatically detached from the <tt class="classname">Chapter</tt>
thanks to the <tt class="classname">ChapterListener</tt> class'
destructor.</p>
<p>Key benefits:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The sought after Java style interface</p>
</li>
<li>
<p>Can listen to more than one different type of <tt class=
"classname">Notifier</tt> because you can inherit from different
adaptor classes</p>
</li>
</ul>
</div>
<p>Drawbacks:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Have to write an adaptor for each class you want a Java-like
interface for</p>
</li>
<li>
<p>You need to create a second object which <span class=
"bold"><b>must</b></span> be contained by value (not actually a
drawback, but we have no way of <span class=
"emphasis"><em>enforcing</em></span> this relationship in the
code)</p>
</li>
<li>
<p>You can only listen to one <tt class="classname">Chapter</tt> at
once</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e230" id="d0e230"></a>Design 6:
Extra parameters</h2>
</div>
<p>We can fix the last disadvantage very easily: we only need to
add an extra parameter to the <tt class=
"classname">ListenerInterface</tt> methods that specifies which
<tt class="classname">Notifier</tt> caused the event:</p>
<pre class="programlisting">
class ChapterListenerInterface
{
  public:
    virtual void ~ChapterListenerInterface()        = 0;
    virtual void chapter_titleAltered(Notifier *src)   = 0; //(*)
    virtual void chapter_noPagesAltered(Notifier *src) = 0; //(*)
    virtual void chapter_deleted(Notifier *src)      = 0; //(*)
  private:
    ChapterListenerInterface() {}
    ChapterListenerInterface(const ChapterListenerInterface &amp;);
    ChapterListenerInterface &amp;operator=(const ChapterListenerInterface &amp;);
};
</pre>
<p>There is a slightly annoying 'feature' of this design: we cannot
pass <tt class="classname">Chapter</tt> pointers into the functions
marked (<span class="bold"><b>*</b></span>), only the base
<tt class="classname">Notifier</tt> pointers. The <tt class=
"classname">Listener</tt> class interface forces everything to be
cast to the common <tt class="classname">Notifier</tt> type,
despite the fact that we know that in this interface the source
object will most certainly be a <tt class="classname">Chapter</tt>
pointer.</p>
<p>There is not a lot we can do to get around this. We could
certainly perform a <tt class=
"literal">dynamic_cast</tt><sup>[<a name="d0e267" href=
"#ftn.d0e267" id="d0e267">3</a>]</sup> in the <tt class=
"classname">ChapterListener</tt>'s updated method to convert the
<tt class="classname">Notifier*</tt> to a <tt class=
"classname">Chapter*</tt>. But it is not a very good solution - for
every event raised we have to perform RTTI, which is an expensive
operation that we should avoid if at all possible (and of course,
some environments which like to compile without RTTI will not
cope). For this reason, we stick with the <tt class=
"classname">Notifier*</tt>. If the user needs the real <tt class=
"classname">Chapter*</tt> they can perform the cast themselves.</p>
<p>In order to <tt class="methodname">attach</tt> to more than one
<tt class="classname">Chapter</tt>, we need to contain more than
one <tt class="classname">ChapterListener</tt> adaptor object,
since each of these adaptor classes can only listen to one
<tt class="classname">Notifier</tt>.</p>
<p>Since we really want the <tt class="classname">Book</tt> object
to listen to a variable number of <tt class=
"classname">Chapter</tt>s, extra work is needed in the
implementation of the adaptor class. In this kind of situation we
really need to balance this effort and decide whether an adaptor
class is really warranted.</p>
<p>Key benefits:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Can now listen to more than one object of the same type</p>
</li>
</ul>
</div>
<p>Drawbacks:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The interface passes a base pointer who's real type you know -
this requires us to use RTTI, or lump it</p>
</li>
<li>
<p>Can only attach one adaptor to one <tt class=
"classname">Notifier</tt></p>
</li>
<li>
<p>Extra work required to listen to a variable number of <tt class=
"classname">Notifier</tt>s</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e343" id="d0e343"></a>Design 7:
More generic</h2>
</div>
<p>We must write quite a lot of code for each <tt class=
"classname">Listener</tt> adaptor. Can we use templates to remove
some of that redundancy? If we can then we will gain a number of
benefits:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>less typing for each implementation</p>
</li>
<li>
<p>less chance of bugs, since there are fewer lines of code</p>
</li>
<li>
<p>clearer design to understand</p>
</li>
</ul>
</div>
<p>We introduce the <tt class="classname">Listener</tt> adaptor
<span class="emphasis"><em>class concept</em></span>. A class
concept describes what facilities a class should provide with no
syntactic backing; it is often used to describe what a template
parameter type should be able to do. The STL, for example, contains
many class concepts, such as the 'forward iterator'. An instance of
our adaptor class must contain a number of items - <tt class=
"literal">typedef</tt>s, integer definitions, and so on. The idea
is shown below:</p>
<pre class="programlisting">
// The ChapterListenerInterface is based on the ListenerAdpator class concept

class ChapterListenerInterface
{
  public:
    typedef Chapter Notifier_type;  // Defines the source Notifer
    const int no_aspects = 2;     // The number of aspects
    enum              // enum of all aspects
    {
      chapter_titleAltered,
      chapter_noPagesAltered
    }
// typedef to provide the type of method called  

    typedef   ChapterListenerInterface::*callback_t)(Notifier_type*); 

// Using it we define an array of updated callbacks and a single deleted callback
    static const callback_t updated_callback[];updated callbacks
    static const callback_t deleted_callback; callback

// After the mandatory items we define the abstract interface for callbacks

    void chapter_titleAltered(Notifier *src)   = 0;
    void chapter_noPagesAltered(Notifier *src) = 0;
    void chapter_deleted(Notifier *src)    = 0;
};
</pre>
<p>In a <tt class="filename">.cpp</tt> file, we define the callback
array:</p>
<pre class="programlisting">
ChapterListenerInterface::callback_t
ChapterListenerInterface::updated_callback
      [ChapterListenerInterface::no_aspects]  =
    {
      &amp;ChapterListenerInterface::chapter_titleAltered,
      &amp;ChapterListenerInterface::chapter_noPagesAltered,
};

ChapterListenerInterface::deleted_callback = &amp;ChapterListenerInterface::chapter_deleted;
</pre>
<p>It is a shame that we have to do this in a separate <tt class=
"filename">.cpp</tt> file - it would be nice to have defined the
callbacks in the class declaration. However, C++ only allows us to
define static constant integers in a class declaration, and
certainly not arrays.</p>
<p>Now we can use this adaptor class by containing an adaptor
object that uses this <tt class=
"classname">ChapterListenerInterace</tt>:</p>
<pre class="programlisting">
class Book
{
  public:
    Book() : chapterListener(this) { chapterListener.attachTo(&amp;chapter); }
  private:
    Chapter    chapter;
    ListenerAdaptor&lt;ChapterListenerInterface&gt; chapterListener;
};
</pre>
<p>So we need to see what this <tt class=
"classname">ListenerAdaptor</tt> looks like. Well, I am sure you
could work out that it looks like this:</p>
<pre class="programlisting">
template &lt;class ifclass&gt;
class ListenerAdaptor : public Listener
{
  public:

    ListenerAdaptor(ifclass *dest) : Listener(), src(0), dest(dest) {}

    virtual ~ListenerAdaptor() { detach(); }

    void attachTo(typename ifclass::Notifier_type *src)
    {
      if (src) detach();
      this-&gt;src = src;
      src-&gt;attach(this);
    }
 
    void detach()
    {
      if (src)
      {
        src-&gt;detach(this);
        src = 0;
      }
    }

  private:

    virtual void updated(Notifier *source, int aspect)
    {
      if (aspect &lt; ifclass::no_aspects)
        (dest-&gt;*ifclass::callback_table[aspect])(source);
    }

    virtual void deleted(Notifier *source)
    {
      (dest-&gt;*ifclass::callback_deleted)(source);
      src = 0;
    }

  private:
    typename ifclass::Notifier_type *src;
    ifclass *dest;
};
</pre>
<p>It looks like quite a lot to take in one step, but doing this
reduces the amount of effort that is needed to add new <tt class=
"classname">ListenerAdaptor</tt> interfaces to the system since the
<tt class="classname">ListenerAdaptor</tt> template class already
does all the hard work.</p>
<p>Note the use of <tt class="literal">typename</tt> in the code
above, which is needed to tell the compiler that certain
definitions are actually type names that will be pulled in from the
ifclass definition at template instantiation time. If we do not
supply this hint the compiler will assume that <tt class=
"literal">ifclass::Notifier_type</tt>, for example, is either a
method or variable in the template, and complain bitterly at the
apparent syntactic error.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e416" id="d0e416"></a>Design 8:
Combining the adaptor and interface</h2>
</div>
<p>Another problem cited in 'design 5' is that we have to create
separate interface and adaptor classes. We also have to contain the
adaptor object by value. Could we not simply roll these two classes
together? When inheriting from the listener interface class you
would then also get the event conversion code for free.</p>
<p>We are forgetting our clever use of templates for the
moment.</p>
<p>To illustrate this approach we will deviate from the <tt class=
"classname">Book</tt>/<tt class="classname">Chapter</tt>/<tt class=
"classname">Page</tt> example and consider a couple of example
classes imaginatively called <tt class="classname">A</tt> and
<tt class="classname">B</tt>. They are both <tt class=
"classname">Notifier</tt>s, both contain <tt class=
"literal">enum</tt> aspect definitions, and both have a couple of
methods that do something to cause a notification to be sent.
Marvellously contrived.</p>
<pre class="programlisting">
class NotifierA : public Notifier
{
  public:
    enum {   a_1, a_2 };
    void do_1() { notify(a_1); }
    void do_2() { notify(a_2); }
};

class NotifierB : public Notifier
{
  public:
    enum {b_1, b_2 };
    void do_1() { notify(b_1); }
    void do_2() { notify(b_2); }
};
</pre>
<p>So if we write an adaptor class that is also an abstract
interface class, we get the following:</p>
<pre class="programlisting">
class ListenerA : public Listener
{
  protected:
    ListenerA() : src(0) {}
    ~ListenerA() { detach(); }
    void attachTo(NotifierA *a)
    {
      if (src) src-&gt;detach(this);
      src = a;
      src-&gt;attach(this);
    }
    // detach is implemented as before
    virtual void a_1(Notifier *src) = 0;
    virtual void a_2(Notifier *src) = 0;
  private:
    NotifierA *src;
    virtual void updated(Notifier *src, int aspect)
    {
      if (src == this-&gt;src) {
        switch (aspect) {
          case NotifierA::a_1: a_1(src); break;
          case NotifierA::a_2: a_2(src); break;
        }
      }
    }
    // deleted is implemented similarly
};
</pre>
<p>Repeat this kind of class for a <tt class=
"classname">ListenerB</tt>. (In this case you'll largely be
swapping <tt class="classname">A</tt>s for <tt class=
"classname">B</tt>s and <tt class="classname">a</tt>s for
<tt class="classname">b</tt>s.)</p>
<p>We now need a concrete class that illustrates how we can listen
to a <tt class="classname">NotifierA</tt>, to show how little
effort is needed. Let us call it <tt class=
"classname">ConcreteListenerA</tt> for want of a better name.</p>
<pre class="programlisting">
class ConcreteListenerA : public ListenerA
{
  public:
    ConcreteListenerA()
    {
      attachTo(&amp;_a);
    }
    virtual void a_1(Notifier *) { cout &lt;&lt; &quot;a_1\n&quot;; }
    virtual void a_2(Notifier *) { cout &lt;&lt; &quot;a_2\n&quot;; }
    NotifierA *a() { return &amp;_a; }
  private:
    NotifierA _a;
};
</pre>
<p>With a little harness to show how this works:</p>
<pre class="programlisting">
int main() {
  ConcreteListenerA cl_a;
  cl_a.a()-&gt;do_1();
  cl_a.a()-&gt;do_2();
}
</pre>
<p>This produces the output you would expect:</p>
<pre class="screen">
a_1
a_2
</pre>
<p>Well that is a bit of a success: we now have an interface class
that also acts as an adaptor. But (there's always a 'but') what
happens when you want to listen to more than one kind of <tt class=
"classname">Notifier</tt>? Let us say that we have a <tt class=
"classname">ConcreteListenerAB</tt> that inherits from both
<tt class="classname">ListenerA</tt> and <tt class=
"classname">ListenerB</tt>.</p>
<p>The problem we now have is that <tt class=
"classname">ConcreteListenerAB</tt> has two <tt class=
"methodname">attachTo</tt> methods. They are ambiguous. We'd use
them by calling <tt class="methodname">attachTo(this)</tt>, but
which <tt class="methodname">attachTo</tt> do we intend to call?
One will attach to a <tt class="classname">NotifierA</tt> and one
to a <tt class="classname">NotiferB</tt>. The compiler isn't
psychic enough to deduce which one we mean, since the this pointer
could be equally converted into either type. We can get around this
just by being a little bit more explicit:</p>
<pre class="programlisting">
class ConcreteListenerAB : public ListenerA, public ListenerB
{
  public:
    ConcreteListenerAB()
    {
      ListenerA::attachTo(&amp;_a); // have to specify
      ListenerB::attachTo(&amp;_b); // which attachTo to call
    }
    virtual void a_1(Notifier *) { cout &lt;&lt; &quot;ab a_1\n&quot;; }
    virtual void a_2(Notifier *) { cout &lt;&lt; &quot;ab a_2\n&quot;; }
    virtual void b_1(Notifier *) { cout &lt;&lt; &quot;ab b_1\n&quot;; }
    virtual void b_2(Notifier *) { cout &lt;&lt; &quot;ab b_2\n&quot;; }
    NotifierA *a() { return &amp;_a; }
    NotifierB *b() { return &amp;_b; }
  private:
    NotifierA _a;
    NotifierB _b;
};

int main() {
  ConcreteListenerAB cl_ab;
  cl_ab.a()-&gt;do_1();
  cl_ab.a()-&gt;do_2();
  cl_ab.b()-&gt;do_1();
  cl_ab.b()-&gt;do_2();
}
</pre>
<p>This harness does what we expect, proving that the system
works:</p>
<pre class="screen">
ab a_1
ab a_2
ab b_1
ab b_2
</pre>
<p>So the approach works, but you need to be a little bit more
explicit to the compiler. Not necessarily a bad thing. The user
does have to think carefully about what they are attaching to,
though.</p>
<p>There is, however, another problem with this approach. What if
you want to attach to more than one <tt class="classname">A</tt> or
<tt class="classname">B</tt>? Using this inheritance based approach
we can't contain multiple <tt class="classname">Listener</tt>
adaptor classes, and so can only <tt class=
"methodname">attachTo</tt> one <tt class="classname">A</tt> or
<tt class="classname">B</tt> at once. That is unless you do extra
work to implement a more clever adaptor class.</p>
<p>Take care that the inheritance of a <tt class=
"classname">Listener</tt> adaptor class must not be virtual. This
would mean that rather than having two updated methods which are
called according to the context of the pointer (i.e. in the example
above <tt class="classname">ConcreteListenerAB</tt> have both a
<tt class="methodname">ListenerA::updated</tt> and <tt class=
"methodname">ListenerB::updated</tt> that are called by the
<tt class="classname">NotifierA</tt> class and <tt class=
"classname">NotifierB</tt> class respectively) you would only have
the one <tt class="methodname">updated</tt> method. In this method
you would have to tediously delegate each event by hand.</p>
<p>Key benefits:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Fewer classes on the system, easier to understand</p>
</li>
</ul>
</div>
<p>Drawbacks:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Can only conveniently listen to one of each type of <tt class=
"classname">Notifier</tt></p>
</li>
<li>
<p>Still have to write logic for each type of Listener, and there
is quite a lot of that</p>
</li>
<li>
<p>Have to be careful not to use virtual inheritance</p>
</li>
</ul>
</div>
<p>Despite there being more disadvantages listed than advantages, I
think that overall this is a pretty good approach, if we can
prevent the need for so much legwork...</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e594" id="d0e594"></a>Design 9:
More generic (again)</h2>
</div>
<p>The problem with the above approach, of course, is that you have
to write the <tt class="methodname">updated</tt> and <tt class=
"methodname">deleted</tt> methods for each interface. As in 'design
7', we're really after something a little more generic. Call the
template fairies again.</p>
<p>Ironically, the code for a generic version of this approach is
very similar to the previous generic code. We have to split the
single class back into an adaptor interface class, and the generic
adaptor template class. When implementing this you need to override
each pure virtual method, and provide an array of callbacks. This
is shown in the code below.</p>
<pre class="programlisting">
class AdaptorA
{
  public:
    typedef NotifierA Notifier_type;
    static const int no_aspects  = 2;
    virtual void a_1(Notifier *src) = 0;
    virtual void a_2(Notifier *src) = 0;
    virtual void a_deleted(Notifier *src) = 0;
};

template &lt;class if_type&gt;
class ListenerAdaptor : public if_type, public Listener {
  public:
    ListenerAdaptor() : src(0) {}
    typedef if_type Listener_type;
    typedef void (Listener::*callback_t)(Notifier *);
    static const callback_t updated_callback[Listener_type::no_aspects];
    static const callback_t deleted_callback;

    void attachTo(typename Listener_type::Notifier_type *n){
      if (src) src-&gt;detach(this);
      src = n;
      src-&gt;attach(this);
    }
    void detach(){
      if (src)
      {
        src-&gt;detach(this);
        src = 0;
      }
    }
    virtual void updated(Notifier *n, int aspect){
      if (aspect &lt; Listener_type::no_aspects)(this-&gt;*updated_callback[aspect])(n);
    }
    virtual void deleted(Notifier *n){ (this-&gt;*deleted_callback)(n); }

  private:
    typename Listener_type::Notifier_type *src;
};

const ListenerAdaptor &lt;AdaptorA&gt;::callback_t
ListenerAdaptor&lt;AdaptorA&gt;::updated_callback[AdaptorA::no_aspects] 
                            = {&amp;AdaptorA::a_1, &amp;AdaptorA::a_2 };
const ListenerAdaptor&lt;AdaptorA&gt;::callback_t
                ListenerAdaptor&lt;AdaptorA&gt;::deleted_callback = &amp;AdaptorA::a_deleted;

class ConcreteAdaptorA : public ListenerAdaptor&lt;AdaptorA&gt;
{
  public:
    ConcreteAdaptorA()       { attachTo(&amp;a); }
    void do_something()       { a.notify_1(); }
    virtual void a_1(Notifier *)   { cout &lt;&lt; &quot;adaptor a_1\n&quot;; }
    virtual void a_2(Notifier *)   { cout &lt;&lt; &quot;adaptor a_2\n&quot;; }
    virtual void a_deleted(Notifier *)  { cout &lt;&lt; &quot;adaptor a_deleted\n&quot;; }

  private:
    NotifierA a;
};

int main() {
  ConcreteAdaptorA ca_a;
  ca_a.do_something();
}
</pre>
<p>Key benefits:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Less work involved in adding a new <tt class=
"classname">Listener</tt> adaptor</p>
</li>
<li>
<p>Despite splitting into two class again, inheritance prevents the
messy containment of the adaptor</p>
</li>
</ul>
</div>
<p>Drawbacks:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>We are back to two classes - darn!</p>
</li>
<li>
<p>You end up implementing bits of the two different classes for
each adaptor - somewhat confusing</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e630" id="d0e630"></a>Further
exploration</h2>
</div>
<p>I think that I have probably used up enough paper on this
discussion of the observer pattern, but there is so much more we
could discuss. I leave a few parting ideas as excercises for the
interested reader:</p>
<p>Is it possible to templatize the <tt class=
"classname">Notifier</tt> class (as we tried to do in the first
article), using the <tt class="classname">Listener</tt> adaptor as
a template type? After having done this (if possible), can we
convert that <tt class="methodname">updated(int aspect)</tt> to
<tt class="methodname">updated(Listener_type::callback_t
dest)</tt>?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e649" id="d0e649"></a>Other
Issues</h2>
</div>
<p>There are some other issues to do with using the observer design
pattern that have arisen:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><tt class="classname">Listener</tt>s inheriting from <tt class=
"classname">Listener</tt>s</p>
<p>Let us say the <tt class="classname">Glossary</tt> class
inherits from <tt class="classname">Chapter</tt>. <tt class=
"classname">Glossary</tt> gets its <tt class=
"classname">Listener</tt> capabilities indirectly via <tt class=
"classname">Chapter</tt>.</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/observer%20pattern%20pete%20goodliffe%202.png" align=
"middle"></div>
<p>How do we create a <tt class="classname">GlossaryListener</tt>?
We need to ensure that each aspect number is unique, including
being unique between the <tt class="classname">ChapterListener</tt>
class and the <tt class="classname">GlossaryListener</tt> class.
The approach I adopted is as follows (using the 'design 7'
outline).</p>
<pre class="programlisting">
class GlossaryListener : public ChapterListener
{
  public:
    enum 
    {
      glossary_defnAdded = ChapterListener::no_aspects,
      glossary_defnRemoved
    }
    ... // and all the other stuff
};
</pre>
<p>The implementation of an interface hierarchy of <tt class=
"classname">Listener</tt>s is, seemingly, always untidy.</p>
</li>
<li>
<p>Build dependancies</p>
<p>It should be noted that the addition of these adaptor classes
tends to increase the build dependencies in the system.</p>
</li>
<li>
<p>Attaching to a variable number of <tt class=
"classname">Notifier</tt>s</p>
<p>These designs are not so useful if you want to attach to a
number of objects of the same class. <tt class=
"classname">Book</tt> will want to attach to any number of
<tt class="classname">Chapter</tt>s. These are only really useful
it you know how many objects you will be attached to. The adaptors
can be extended to cope with this kind of use - I leave it as an
exercise for the reader, who should also judge whether it is worth
it.</p>
</li>
<li>
<p>No <tt class="methodname">updated</tt> aspects</p>
<p>What happens if a class has no interesting <tt class=
"methodname">updated</tt> aspects, but you want to be informed when
it is deleted. If its <tt class="classname">Listener</tt> adaptor
class defines <tt class="varname">no_aspects</tt> as 0 the code
will not compile - C++ doesn't allow you to create an array with
zero elements. (Well, you can if you are creating it using
<tt class="literal">new</tt>, but that's another story). You will
need a strategy to get around this. Perhaps the easiest is just to
define a dummy <tt class="methodname">updated</tt> reason code.</p>
</li>
<li>
<p>Choice of inheritance type</p>
<p>In these implementations I have used public inheritance. You may
choose to use private inheritance if it suits you. If you're not
sure what the difference is, I urge you to go and find out now!</p>
</li>
<li>
<p>Reviewing safe (design 3) vs. unsafe (design 4)</p>
<p>Using the adaptor is so much like the 'safety' model I presented
in [<a href="#Goodliffe">Goodliffe</a>] that I think that my
preferences have moved towards it (except, perhaps, renaming attach
as <tt class="methodname">attachTo</tt>).</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e757" id=
"d0e757"></a>Conclusions</h2>
</div>
<p>I am not sure that it will be possible to construct the perfect
observer implementation. I am sure that if I were to ever find one
I'd have spent so much effort on it I will probably never have
written any other code.</p>
<p>In exploring this set of new implementations I hope that we've
gained a better understanding of the observer pattern, and the
situations in which it could be used. I hope that we have also
explored some other useful ideas ('class concepts' and adaptors)
and got a feel for some more 'real worldf C++ coding.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e764" id="d0e764"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Goodliffe" id="Goodliffe"></a>
<p class="bibliomixed">[Goodliffe] Pete Goodliffe. Experiences of
Implementing the Observer Design Pattern (Part 1). In: Overload 37,
2000.</p>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] Gamma, Helm, Johnson, Vlissades.
Design Patterns - Elements of Reusable Object-Oriented Software.
Addison-Wesley, 1995.</p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e87" href="#d0e87" id=
"ftn.d0e87">1</a>]</sup> One article full of exhibitionists and
voyeurs is quite enough!</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e137" href="#d0e137" id=
"ftn.d0e137">2</a>]</sup> The adaptor is another design pattern in
the GoF book [<a href="#GoF">GoF</a>].</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e267" href="#d0e267" id=
"ftn.d0e267">3</a>]</sup> In fact since we're very sure that the
parameter is a <tt class="classname">Chapter*</tt> we could employ
a <tt class="literal">static_cast</tt>. I am not sure that this
isn't bad form though - and it definitely will not work if the
<tt class="classname">Chapter</tt> uses virtual inheritance from
the <tt class="classname">Notifier</tt>.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
