    <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 1)</title>
        <link>https://members.accu.org/index.php/journals/488</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 #37 - May 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/c167/">37</a>
                    (7)
<br />

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

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

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

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

                    -                        <a href="https://members.accu.org/index.php/journals/c167+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 1)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 May 2000 17:50:57 +01:00 or Tue, 02 May 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>This article describes my experiences of applying the observer
design pattern [<a href="#GoF">GoF</a>] in a C++ library. I present
it not as an authoritative tutorial on how to use the observer (it
isn't) but as fuel for discussion. I hope that my experiences will
be beneficial to others.</p>
<p>The C++ library being developed was based on a much older
version. This older library required the user to maintain
consistency between a number of objects by using the API in a
particular way. This is the sure sign of a badly designed API. The
obvious solution to the problem was to ensure that the objects
maintained their consistency themselves - requiring them to notify
each other of certain state changes.</p>
<p>This is a classic context for the observer pattern, and a number
of implementation approaches for this pattern were considered, with
varying success. This article presents these implementations.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e29" id="d0e29"></a>What is the
observer pattern?</h2>
</div>
<p>The observer pattern is a means of implementing object
notification in a generic way. It is a useful method of decoupling
objects, that is breaking the hard-coded ties between them. Using
this pattern, an object does not need to know who/what is
interested in notifications it may wish to publish. From this it
follows that the interested parties may even change at run
time.</p>
<p>We will see the structure of interacting classes in this pattern
later in this article.</p>
<p>There are issues with the observer pattern that are largely
ignored when it is described, the most important arising from its
compile-time decoupling/run-time coupling nature. It can be very
hard to find bugs related to the pattern implementation - who is to
know what is/is not currently listening to a particular object? Any
variation in run-time behaviour from what is expected is much
harder to track down than a coding fault that shows up clearly at
compile-time.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e38" id="d0e38"></a>Design 1:
Java-like listener interfaces</h3>
</div>
<p>I have spent quite some time working in Java (actually,
implementing the language) and so was accustomed to the Java event
model implementation. My first observer design closely paralleled
this mechanism. As it was to turn out it does not translate neatly
into C++ - the idioms of one language rarely stretch into
another.</p>
<p>The Java idiom uses the language's <tt class=
"literal">interface</tt> feature. interfaces are equivalent to pure
abstract classes in C++ and are an essential part of the Java
equivalent of multiple inheritance - you can only inherit multiply
from <tt class="literal">interface</tt>s. These particular
<tt class="literal">interface</tt>s, known as listener interfaces
are defined to receive update events through their member
functions. For example, an AWT<sup>[<a name="d0e54" href=
"#ftn.d0e54" id="d0e54">1</a>]</sup> <tt class=
"classname">MouseListener</tt> looks something like the
following.</p>
<pre class="programlisting">
public interface MouseListener {
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
// ...and so on...
}
</pre>
<p>A class that wants to listen to mouse events implements the
<tt class="classname">MouseListener</tt> interface and attaches
itself to an AWT user interface component using a method in the
<tt class="classname">java.awt.component</tt> class:</p>
<pre class="programlisting">
public synchronized void addMouseListener(MouseListener l);
</pre>
<p>This means that a calling mechanism must be implemented in the
notifying class for each different type of listener interface.</p>
<p>In the C++ design based on this Java idiom templates were
introduced to make the code generic - it is easy to produce a
version of this idiom tailored to one particular listener class but
much more beneficial to make it a generic mechanism. The possible
savings from doing this include reduction in development time, code
size, maintenance costs, and the possible number of bugs.</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%201.png"
align="middle"></div>
<p>Notifier is defined to be the class that publishes information
about its state changes. There exists some type of listener class
that receives this information.</p>
<p>The Notifier class uses the type of listener class as it's
template parameter. In this way any class that needs to publish
state change information can provide an abstract listener interface
class and then inherit publicly from a Notifier parameterised by
this listener interface type.</p>
<p>An implementation of this listener class can attach/detach
itself to the Notifier (which keeps an internal list of which
listeners are attached, probably with an STL list). The class
implementing the Notifier can then call its protected notify method
whenever an event occurs.</p>
<p>To understand this better we need to see it in action. For a
particular case let's say we have a Voyeur class that watches
objects of the Exhibitionist class and wants to be kept abreast of
their changes. The design would be used as follows.</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%202.png"
align="middle"></div>
<p>For some <tt class="classname">Exhibitionist</tt>, <tt class=
"varname">e</tt>, that the <tt class="classname">Voyeur</tt> object
uses, it will call <tt class="literal">e-&gt;attach(this)</tt>. So
if in the future some external agent calls <tt class=
"methodname">changeA</tt> on the <tt class=
"classname">Exhibitionist</tt> it uses the notify member function
to send an <tt class="methodname">aChanged</tt> event to all
attached <tt class="classname">ExhibitionistListener</tt>s,
including the <tt class="classname">Voyeur</tt> object.</p>
<p>This appears to be quite a neat design, the only issue left
unresolved is how to implement the notify method in C++. We need to
supply an argument to notify that specifies which method on the
<tt class="classname">ExhibitionistListener</tt> to call.</p>
<p>This is a candidate for the use of a <span class=
"emphasis"><em>function object (or functor)</em></span>. These are
classes which may be called via their function operator, <tt class=
"methodname">operator()</tt>. We use function objects like the one
shown below. There is an issue over where it should be placed in
the <tt class="literal">namespace</tt>/<tt class=
"literal">class</tt> hierarchy. The logical place is as a public
member of the <tt class="classname">ExhibitionistListener</tt>
class.</p>
<pre class="programlisting">
class call_aChanged {
public:
  operator()(ExhibitionistListener *e){
    e-&gt;aChanged();
  }
};
</pre>
<p>Now when the <tt class="classname">Exhibitionist</tt> calls
notify it uses code like:</p>
<pre class="programlisting">
notify(ExhibitionistListener::call_aChanged());
</pre>
<p>If the listeners are held in an STL <tt class=
"classname">list&lt;ExhibitionistListener&gt;</tt>, notify can be
easily implemented using a template member function thus:</p>
<pre class="programlisting">
template &lt;class Functor&gt;
Notifier::notify(Functor f) {
  for_each(listeners.begin(),
       listeners.end(), f);
}
</pre>
<p>If the listener event method needs some parameter (often the
source <tt class="classname">Notifier</tt> is required at the very
least if the <tt class="classname">Voyeur</tt> listens to several
<tt class="classname">Exhibitionist</tt>s at once) then this can be
supplied in the constructor of the functor, e.g.</p>
<pre class="programlisting">
class call_bChanged {
public:
  call_bChanged(int newB) : b(newB) {}
  operator()(ExhitionistListener *e){
    e-&gt;bChanged(b);
  }
private:
  int b;
}
</pre>
<p>This is a fairly neat design, allowing you to create Java-like
listener interfaces. It is easy to use. Using multiple inheritance
allows the <tt class="classname">Voyeur</tt> to be several
different types of listener and so keep itself up to date with
respect to a number of different types of <tt class=
"classname">Notifier</tt>.</p>
<p>However, there are a number of issues with this design. Consider
the following example in which a new class, <tt class=
"classname">NamedExhibitionist</tt>, acts like an <tt class=
"classname">Exhibitionist</tt> but also adds a stored name
facility.</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%203.png"
align="middle"></div>
<p>So how should the <tt class=
"classname">NamedExhitionistListener</tt> fit into the design? It
could either</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>inherit from <tt class="classname">ExhibitionistListener</tt>
and be used in place of ordinary <tt class=
"classname">ExhibitionistListener</tt>s, or</p>
</li>
<li>
<p>remain distinct from <tt class=
"classname">ExhibitionistListener</tt> and be used in addition to
it</p>
</li>
</ol>
</div>
<p>Neither option is useful. In the case of (1) when the <tt class=
"classname">NamedExhibitionistListener</tt> implementation calls
<tt class="methodname">NamedExhibitionist::attach(this)</tt>, the
this parameter is converted into a base <tt class=
"classname">ExhibitionistListener</tt> pointer. The <tt class=
"classname">NamedExhibitionistListener</tt>'s extra functionality
is not available to the <tt class=
"classname">NamedExhibitionist</tt>, since <tt class=
"methodname">Exhibitionist::notify</tt> cannot call <tt class=
"methodname">nameChanged</tt> on an <tt class=
"classname">ExhibitionistListner</tt>. <tt class=
"literal">dynamic_cast&lt;NamedExhibitionist&gt;</tt> could be
employed by the functor but in often used code it would present a
significant performance hit.</p>
<p>We can try to get around this problem by making <tt class=
"classname">NamedExhibitionist</tt> inherit from both <tt class=
"classname">Exhibitionist</tt> and a new version of the <tt class=
"classname">Notifier</tt>, a <tt class=
"classname">Notifier&lt;NamedExhibitionistListener&gt;</tt>. By
doing this though, things get really nasty. The <tt class=
"classname">NamedExhibitionist</tt> has two <tt class=
"methodname">attach</tt> methods. When you call <tt class=
"methodname">attach</tt>, which copy is called? The <tt class=
"methodname">NameExhibitionist::attach</tt> hides its base class'
method. So it is necessary to qualify the attach with a class name
and call either <tt class="methodname">Exhibitonist::attach</tt> or
<tt class="methodname">NamedExhibitonist::attach</tt> on the
<tt class="classname">NamedExhibitionist</tt> object.</p>
<p>Similarly, the compiler cannot deduce which notify to call, and
so the <tt class="classname">NamedExhibitionist</tt> needs to call
<tt class=
"methodname">Notifer&lt;NamedExhibitionistListener&gt;::notify(NamedExhibionistListener::call_nameChanged())</tt>.
Euch. Also, when using this method, if a <tt class=
"classname">Voyeur</tt> cares both about the basic <tt class=
"classname">Exhibitionist</tt> changes and the name changes in
<tt class="classname">NamedExhibitionist</tt> then it has to attach
itself twice to the object.</p>
<p>This Java-like method still works but in certain cases the
<tt class="classname">Notifier</tt> API is burdensome. As stated
before, this is a sure indication of a bad design.</p>
<div class="variablelist">
<dl>
<dt><span class="term">Key benefits</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>For simple class hierarchies it is clear and easy to use.</p>
</li>
<li>
<p>Provides Java-like listener interfaces, one method is called for
each event that could occur, no unnecessary switches on event
type.</p>
</li>
<li>
<p>Information describing the event can be passed to listener
methods.</p>
</li>
</ul>
</div>
</dd>
<dt><span class="term">Drawbacks</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Requires a functor for each listener method.</p>
</li>
<li>
<p>Although a class can listen to any number of different
<tt class="classname">Notifier</tt>s, it can only be one kind of
<tt class="classname">Notifier</tt> without incurring a burdensome
API.</p>
</li>
</ul>
</div>
</dd>
</dl>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e322" id="d0e322"></a>Design 2: Remove
templates</h3>
</div>
<p>A different approach is to get rid of the parameterised
<tt class="classname">Notifier</tt> and have a single <tt class=
"classname">Listener</tt> base interface class. This avoids
problems involved when adding extra functionality to the
Exhibitionist through inheritance. In doing this we lose the
ability to have different methods called for each kind of event
raised, which was the Java listener style.</p>
<p>We can try to compensate for this by using an Event base class
to represent the kind of event that has occurred.</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%204.png"
align="middle"></div>
<p>Now applying this framework to the previous example:</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%205.png"
align="middle"></div>
<p>This kind of hierarchy involving a set of congruent class trees
is known as covariant typing. Practically the only language that
provides any support for <span class="emphasis"><em>covariant
typing</em></span> is Eiffel. There are different schools of
thought on whether it is a good or bad thing. However, C++ provides
no support for it and so using it is not very useful in this
context.</p>
<p>If a <tt class="classname">Listener</tt> is attached to a
<tt class="classname">NamedExhibitionist</tt> and gets notified of
an action through a call to its update method, it will have to
employ RTTI to deduce what sort of <tt class="classname">Event</tt>
has been passed through to it. This is not a very clever mechanism
for such a often-performed task. We will also need to have some
additional mechanism for representing the information relating to
each type of event within each <tt class="classname">Event</tt>
class.</p>
<p>If you think that this is a good way to code then you should be
forced to write in BASIC for the rest of your life.</p>
<div class="variablelist">
<dl>
<dt><span class="term">Key benefits</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Any class can listen to more than one <tt class=
"classname">Notifier</tt>.</p>
</li>
<li>
<p>Any <tt class="classname">Notifier</tt> can publish more than
one kind of Event.</p>
</li>
</ul>
</div>
</dd>
<dt><span class="term">Drawbacks</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Needs RTTI and a sick mind to be used.</p>
</li>
</ul>
</div>
</dd>
</dl>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e386" id="d0e386"></a>Design 3:
Simplicity</h3>
</div>
<p>The practical solution to the problem was to strip back all the
fancy bits and have a simple <tt class="classname">Notifier</tt>,
and a simple <tt class="classname">Listener</tt>. The best designs
are nearly always the most simple. This is the class hierarchy
used:</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%206.png"
align="middle"></div>
<p>This allows an object to listen to as many <tt class=
"classname">Notifier</tt>s as required - the source is identified
in the event methods. There is no problem with being more than one
kind of <tt class="classname">Notifier</tt> - there is only
one.</p>
<p>A reason code (<tt class="varname">rc</tt>) describing the type
of change is passed around by <tt class="methodname">notify</tt>.
The definitions for this integer could be held as <tt class=
"type">static const int</tt>s in either the <tt class=
"classname">Notifier</tt> imple-mentation, or in some related
scope. If the <tt class="classname">Listener</tt> is attached to
more than one 'kind' of <tt class="classname">Notifier</tt> it can
inspect the source reference it is passed to see which type of
object it is (a <tt class="classname">Listener</tt> will always
know what objects it has attached itself to) and interpret the
integer accordingly.</p>
<p>The <tt class="classname">Notifier</tt> has to be passed around
as a parameter otherwise you can only be one kind of <tt class=
"classname">Listener</tt> - it would be impossible to determine
what the integer reference referred to in the presence of more than
one <tt class="classname">Notifier</tt>.</p>
<p>The code for this is fairly simple and looks as follows. Note
that again we use functors as the mechanism for dispatching
messages to <tt class="classname">Listener</tt>s. This time,
though, we only need two.</p>
<pre class="programlisting">
class Notifier;

class Listener {
public:
  virtual ~Listener() {}
  virtual void updated(
        Notifier *source, int rc){}
  virtual void deleted(
                Notifier *source){}
};

class Notifier {
public:
  void attach(Listener *l) 
        { listeners.push_back(l); }
  void detach(Listener *l) 
          { listeners.remove(l); }
protected:
  class NotifyUpdated {
  public:
    NotifyUpdated(Notifier *n, int rc)
        : source(n), rc(rc) {}
    void operator()(Listener *l)
        { l-&gt;updated(source, rc); }
  private:
    Notifier *source;
    int *rc;
  };
  
void notify(int rc = 0) {
  for_each(listeners.begin(),
          listeners.end(),
          NotifyUpdated(this, rc));
  }
private:
  class NotifyDeleted {
  public:
    NotifyDeleted(Notifier *n) 
                    : source(n) {}
    void operator()(Listener *l)
          { l-&gt;deleted(source); }
    private:
      Notifier *source;
  };
  virtual ~Notifier() {
    for_each(listeners.begin(),
            listeners.end(),
            NotifyDeleted(this));
  }
  list&lt;Listener *&gt; listeners;
};
</pre>
<p>Note the addition of the <tt class="methodname">deleted</tt>
event member function in the <tt class="classname">Listener</tt>
which is called by the <tt class="classname">Notifier</tt>'s
destructor. I found that many events tracked by my classes were
'about to be deleted' messages, used to prevent any dangling
references to dead objects existing in the system. It makes sense
to roll these up into a separate event and provide explicit
support.</p>
<p>Another important point to note is the <tt class=
"literal">virtual</tt> destructors. This ensures that when a
<tt class="classname">Notifier</tt> is destroyed the <tt class=
"methodname">deleted</tt> message is sent. Without this code along
the lines of</p>
<pre class="programlisting">
void foo()  {
  Exhibitionist *e = new Exhibitionist();
  Notifier    *n = e;
// ...do something...
  delete n; 
// possibly in another function
}
</pre>
<p>would only call the <tt class="classname">Notifier</tt>
destructor and not the <tt class="classname">Exhibitionist</tt>
destructor as well. This is such a simple piece of C++, yet it's
frightening how often it is overlooked. All destructors in classes
with virtual functions should be declared virtual for this reason.
It is good practice to do this even if you do not think that a
class you are writing will ever be inherited from.</p>
<p>Applying this new framework to the <tt class=
"classname">Exhibitionist</tt>/ <tt class="classname">Voyeur</tt>
classes:</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%207.png"
align="middle"></div>
<p>So the <tt class="classname">Voyeur</tt> object will call attach
on an <tt class="classname">Exhibitionist</tt> object. From then
on, whether it was an <tt class="classname">Exhibitionist</tt> or a
<tt class="classname">NamedExhibitionist</tt>, it will receive all
updates. A parameter may tell it what sort of update occurred.</p>
<p>This design is not as neat as the Java event model, but the
benefits are that it is generic enough, is simple to use and to
understand. We have to be careful, though. In particular we have to
ensure that the definition of integer update reason codes for the
<tt class="classname">NamedExhibitionist</tt> codes must not cross
into the <tt class="classname">Exhibitionist</tt> ones.</p>
<p>I toyed with the idea of inheriting specific kinds of <tt class=
"classname">Listener</tt> that describe the event codes as
shown</p>
<div class="c2"><img src="/var/uploads/journals/resources/observer%20pattern%208.png"
align="middle"></div>
<p>However, this gains us nothing. When a call to attach is made,
it is not possible to check that you are passing the correct type
of <tt class="classname">Listener</tt>. However, non inherited
versions of this class are a neat place to group reason code
values.</p>
<div class="variablelist">
<dl>
<dt><span class="term">Key benefits</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Simple design.</p>
</li>
<li>
<p>It works.</p>
</li>
</ul>
</div>
</dd>
<dt><span class="term">Drawbacks</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The integer reason code is messy.</p>
</li>
<li>
<p>Again, not really the Java listener idiom. Ho hum.</p>
</li>
<li>
<p>Presents a number of possible bug sources - read on...</p>
</li>
</ul>
</div>
</dd>
</dl>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e547" id="d0e547"></a>Design 4:
Safety</h3>
</div>
<p>Using this design for quite some time revealed minor problem
areas, especially when a number of more dynamic classes (whose
objects are frequently created and deleted) used the observer
mechanism. This is an example of the issue mentioned in the
observer pattern introduction - it can be notoriously difficult to
find run-time problems manifested with the observer pattern.</p>
<p>A number of <tt class="classname">Listener</tt>s attach
themselves to more than one dynamically-lived <tt class=
"classname">Notifier</tt>. It is very easy to not override the
default <tt class="methodname">deleted</tt> member function, and so
lose track of which objects still exist and which do not. Errors
can easily occur from trying to dereference a pointer to an object
that you think still exists, but in fact does not. This is problem
must be carefully watched for.</p>
<p>An additional source of bugs with this mechanism is failing to
detach a <tt class="classname">Listener</tt> from a <tt class=
"classname">Notifier</tt> before destroying it. Often a destructor
will have to <tt class="methodname">detach</tt> from a number of
objects, but it is very easy to miss one out.</p>
<p>We can introduce mechanisms to combat this fairly easily with
the following revision to the code:</p>
<pre class="programlisting">
class Notifier {
private:
  void attach(Listener *l)
  void detach(Listener *l)
  virtual ~Notifier();
  friend class Listener
};
class Listener  {
  virtual updated(Notifier *source,
                   int rc) {}
  virtual deleted(Notifier *source){
    attachments.remove(source);
// If you override this, ensure that you 
// perform this operation
  }
protected:
  void attach(Notifier *n) {
    n-&gt;attach(this);
    attachments.push_back(n);
  }
  void detach(Notifier *n) {
    n-&gt;detach(this);
    attachments.remove(n);
  }
  list&lt;Notifier *&gt; attachments;
private:
  virtual ~Listener() {
  for_each(attachments.begin(),
          attachments.end(),
      functor_that_calls_detach(this));
  }
};
</pre>
<p>Now a <tt class="classname">Voyeur</tt> will attach itself to an
<tt class="classname">Exhibitionist</tt> <tt class="varname">e</tt>
with code like the following.</p>
<pre class="programlisting">
attach(e);
</pre>
<p>Note that the <tt class="classname">Listener</tt> is now calling
attach on itself.</p>
<p>The use of friendship is a matter of style, however it ensures
that other classes cannot call <tt class=
"methodname">Notifier::attach</tt> and circumvent this protection
system. We still have a possible hole if the <tt class=
"classname">Listener</tt> implementor overrides the deleted method
but forgets to include the <tt class=
"literal">attachments.remove(source)</tt> line in their
version.</p>
<p>The problem with this solution is that the <tt class=
"classname">Voyeur</tt> implementation will probably keep its own
<tt class="varname">e</tt> pointer for internal use, so the class
will now always have two pointers to <tt class="varname">e</tt>. If
you want this added protection then this is the price you pay.</p>
<p>Personally, I do not use this extra functionality. It is a
matter of debate whether this automatic detachment should be an
application object's responsibility or the library's.</p>
<div class="variablelist">
<dl>
<dt><span class="term">Key benefits</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Safer listener deletion - less chance of leaving dangling
references in Notifiers.</p>
</li>
</ul>
</div>
</dd>
<dt><span class="term">Disadvantages:</span></dt>
<dd>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Two pointers to Notifiers will often be kept.</p>
</li>
</ul>
</div>
</dd>
</dl>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e637" id="d0e637"></a>Other
issues</h3>
</div>
<div class="variablelist">
<dl>
<dt><span class="term">Issue 1:</span></dt>
<dd>
<p>If we use an object that derives from two objects, both of which
are <tt class="classname">Listener</tt>s, then two versions of the
<tt class="classname">Listener</tt> abstract interface will be
inherited. This can lead to all sorts of confusion as to which copy
of the <tt class="classname">Listener</tt> base class is used in
which situation. Fortunately there is a language facility to help
us in this respect: <tt class="literal">virtual</tt>
inheritance.</p>
<p>If we inherit from the <tt class="classname">Listener</tt> class
virtually then we are guaranteed to have only one copy of this base
class. It should be noted that this may produce a small performance
hit due to implementation issues. Virtual inheritance is covered in
depth in section 15.2.4 of [<a href="#Stroustrup">Stroustrup</a>]
and in [<a href="#Meyers">Meyers</a>].</p>
</dd>
<dt><span class="term">Issue 2:</span></dt>
<dd>
<p>The visibility level of the <tt class=
"methodname">Notifier::notify</tt> method is alterable according to
taste. Some implementers choose to make it public. This would mean
that any object is capable of causing a notification from any
<tt class="classname">Notifier</tt>. In my opinion this is a little
strange.</p>
<p>However, it does allow certain operational optimisations. For
example, say you are going to make a number of changes to an
object's state through its member functions. Each of those will
generate a notification, but you would rather get one notification
at the end rather than several one after the other. If it is up to
you to trigger the notification by manually calling <tt class=
"methodname">notify</tt> then you can choose what is sent and when.
The danger with this style of usage, though, is that you will
almost certainly forget to call <tt class="methodname">notify</tt>
at some point and then wonder why your program does not work as
expected.</p>
<p>The observer design can be bent to try to accommodate this kind
of delayed notification, but that is another story&hellip;</p>
</dd>
<dt><span class="term">Issue 3:</span></dt>
<dd>
<p>What you do in a <tt class="methodname">notify</tt> method
should be carefully controlled. You should be aware of any changes
that you make that could cause cascading notifications to be sent,
especially if there is a circular dependency that will cause an
infinite loop.</p>
<p>Another possible cause of difficulty is deleting an object
inside a <tt class="methodname">notify</tt> method. This is
especially likely to cause program instability if you are deleting
(directly or indirectly) the object that caused the notification.
It may be the case that you are not the last object to receive that
particular <tt class="methodname">notify</tt> call. A subsequent
<tt class="classname">Listener</tt> object's <tt class=
"methodname">notify</tt> will be called with a source pointer that
is now invalid. What will happen then is anyone's guess, but we can
be sure that it will not always be pretty.</p>
</dd>
<dt><span class="term">Issue 4:</span></dt>
<dd>
<p>As with any other coding problem, the presence of multiple
threads opens a whole new can of worms. The observer pattern relies
on run-time dependencies, as do multiple threads. This makes the
problem an order of magnitude more difficult.</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e721" id=
"d0e721"></a>Conclusions</h2>
</div>
<p>We've seen a number of different approaches to the
implementation of the observer design pattern. What lessons do we
learn? Even if you are not directly involved with the observer
pattern, there are a number of principles we can walk away
with:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Idioms from one language don't always travel easily into
another.</p>
</li>
<li>
<p>There is more than one way to implement a particular design
pattern - which one you choose will depend on the context in which
you need to apply it.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e733" id="d0e733"></a>Next
time</h2>
</div>
<p>In the next article we'll see how we can extend this <tt class=
"classname">Notifier</tt>/ <tt class="classname">Listener</tt>
framework to get closer to the Java-like interfaces I have been
pining for.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e744" id="d0e744"></a>References</h2>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] Gamma, Helm, Johnson, Vlissades.
<span class="citetitle"><i class="citetitle">Design Patterns -
Elements of Reusable Object-Oriented Software</i></span>.
Addison-Wesley, 1995. Page 293.</p>
</div>
<div class="bibliomixed"><a name="Stroustrup" id="Stroustrup"></a>
<p class="bibliomixed">[Stroustrup] Bjarne Stroustrup. <span class=
"citetitle"><i class="citetitle">The C++ Programming Language
3ed</i></span>. Addison Wesley. Section 15.2.4. Page 396.</p>
</div>
<div class="bibliomixed"><a name="Meyers" id="Meyers"></a>
<p class="bibliomixed">[Meyers] Scott Meyers. <span class=
"citetitle"><i class="citetitle">More Effective C++</i></span>.
Addison Wesley. Item 24, Page 29.</p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e54" href="#d0e54" id=
"ftn.d0e54">1</a>]</sup></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
