    <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  :: Objects for States</title>
        <link>https://members.accu.org/index.php/articles/1403</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">Programming Topics + Overload Journal #73 - Jun 2006</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/c65/">Programming</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/c139/">73</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+139/">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;Objects for States</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 June 2006 11:53:00 +01:00 or Thu, 01 June 2006 11:53:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Originally captured in Design Patterns, Objects for States is described in close conjunction with the Singleton pattern. This article investigates better alternatives for implementing the pattern in C++.</p>
<p><strong>Body:</strong>&nbsp;<h2>
The Singleton connection
</h2>
<p>
</p>
<p>
<em>Design Patterns</em> [<a href="#1">1</a>] includes the name Objects for States only as an alias and the pattern is probably better known for its primary name: State. I prefer the name Objects for States because it expresses both the intent and resulting structure in a much better way. After all, the main idea captured in the pattern is to represent each state as an object of its own.
</p>
<p>
Besides the naming issue, everything starts just fine in the pattern description and nothing indicates that Singleton is about to enter the scene. Not even as <em>Design Patterns</em> discusses implementation issues concerning the lifetime of state-objects do they actually mention Singleton. Turn the page and suddenly the pattern appears in the sample code with each state implemented as Singleton. Later on <em>Design Patterns</em> officially relates the two patterns by concluding that &quot;State objects are often Singletons&quot; [<a href="#1">1</a>]. However true that statement may be, is it a good design decision?
</p>
<h2>
The case against Mr Singleton
</h2>
<p>
The Singleton pattern is on the verge of being officially demoted to anti-pattern status. In order to get the freshest insider information possible, I decided to carry out an interview with the subject himself. Mr Singleton surprised me with his honesty and introspective nature.
</p>
<blockquote>
<p>
&quot;Mr Singleton, you have been accused of causing design damage [<a href="#6">6</a>] and of leading programmers to erroneous abstractions by masquerading your tendencies to global domination as a cool object-oriented solution. What are your feelings?&quot;
</p>
<p>
<b>&quot;I'm just an innocent pattern, I did nothing wrong. I feel truly misunderstood.&quot;</b>
</p>
<p>
&quot;But your class diagram included in <em>Design Patterns</em> looks rather straightforward. It doesn't get simpler than that - one class only - how could anyone possibly misunderstand that?&quot;
</p>
<p>
<b>&quot;Well, that's the dilemma.&quot;</b> He continues with a mystic look on his face: <b>&quot;I look simple but my true personality is rather complex, if I may put it that way.&quot;</b>
</p>
</blockquote>
<p>
I understand he has more to say on the subject. I'll see if we can get further.
</p>
<blockquote>
<p>
&quot;Interesting! Care to elaborate?&quot; It seems like he just waited for this opportunity. Mr Singleton immediately answers, not without a tone of pride in his voice:
</p>
<p>
<b>&quot;Sure, first of all I'm hard to implement.&quot;</b>
</p>
<p>
&quot;Yes, I'm aware of that. Most writings about you are actually descriptions of the problems you introduce. What springs to my mind is, hmm, well, no offence, discussions about killing Singletons [<a href="#9">9</a>], a subject which makes matters even worse. There's also all the multithreading issues with you involved [<a href="#10">10</a>].&quot;
</p>
<p>
<b>&quot;Yeah, right, but my implementation is the minor problem. Can you keep a secret?&quot;</b>
</p>
<p>
&quot;Sure&quot;, I reply crossing my fingers.
</p>
<p>
<b>&quot;Hmm, I shouldn't really mention this, but Design Patterns are over-using me.&quot;</b>
</p>
<p>
&quot;Wow! You mean that you are inappropriately used to implement other patterns?&quot;
</p>
<p>
<b>&quot;Yes, you may put it that way. I mean, part of my intent is to ensure that a class only has one instance. But if an object doesn't have any internal state, then what's the point of using me? If there isn't any true uniqueness constraint, why implement mechanisms for guaranteeing only one, single instance?&quot;</b>
</p>
</blockquote>
<p>
Reflecting on the above dialogue I notice that it describes a common problem with many implementations using Objects for States. In most designs the state objects are stateless, yet many programmers, including my younger self, implement them as Singletons. Sounds like some serious tradeoffs are made. After all, I like to take a test-driven approach and writing unit tests with Singletons involved is a downright scary thought. Mr Singleton agrees:
</p>
<blockquote>
<b>&quot;It's sad, isn't it? You end up solving the solution. Not only does it mean writing unnecessary code and that's a true waste; worse is that I'm wrong from a design perspective too.&quot;</b>
</blockquote>
<p>
There it is! Implementing Objects for States using Singleton is, I quote once more, &quot;wrong from a design perspective&quot;. He said it himself. The good news is that in this case a better design also means less code and less complexity. But before jumping into the details of why and how, let's leave Mr Singleton for a while and recap the details of Objects for States.
</p>
<h2>
Objects for States recap
</h2>
<p>
Objects for States works by emulating a dynamic change of type and the parts to be exchanged are encapsulated in different states. A state transition simply means changing the pointer in the context from one of the concrete states to the other. Consider a simple, digital stop-watch. In its most basic version, it has two states: started and stopped. Applying Objects for States to such a stop-watch results in the structure shown in Figure 1.
</p>
<table class="sidebartable"><tr><td>
<img src="/content/images/journals/ol73/ObjectStates1.gif" width="669" height="155" border="0" alt="Applying Objects for States to a stopwatch program" />
</td></tr><tr><td class="title">Figure 1</td></tr></table>
<p>
Before developing a concrete implementation, let's investigate the involved participants and their responsibilities:
</p>
<ul>
<li><tt>stop_watch</tt>: <em>Design Patterns</em> defines this as the context. The context has a pointer to one of our concrete states, without knowing exactly which one. It is the context that specifies the interface to the clients.</li>
<li><tt>watch_state</tt>: Defines the interface of the state machine, specifying all supported events. Depending upon the problem domain, <tt>watch_state</tt> may also implement default actions for different events. The default actions may range from throwing exceptions and logging to silently ignoring the events (the UML note in Figure 1 shows an example of a default action implemented in the <tt>start()</tt> function that sends a debug trace to standard output).</li>
<li><tt>stopped_state</tt> and <tt>started_state</tt>: These are concrete states and each one of them encapsulates the behaviour associated with the state it represents.</li>
</ul>


<h2>
It depends
</h2>
<p>
<em>Design Patterns</em> includes many examples of good OO designs. An example is its adherence to one of the most important design principles: &quot;Programming to an interface, not an implementation&quot;. In fact all patterns in the catalogue, with one notable pathological exception - Singleton, adhere to this principle. Yet there are some subtle nuances to watch out for. Upon state transitions the pointer in the context has to be changed to the new state. The typical approach is to let each concrete state specify their successor state and trigger the transition. This way each state needs a link back to its context.
</p>
<p>
In its canonical form, Objects for States uses a <tt>friend</tt> declaration to allow states to access their context object. A <tt>friend</tt> declaration used this way breaks encapsulation, but that's not really the main problem; the problem is that it introduces a cyclic dependency between the context and the classes representing states. Such a dependency is an obstacle to unit tests and leads to big-bang integrations, although limited to the micro-universe of the context. Fortunately enough it is rather straightforward to break this dependency cycle. The first step is to introduce an interface to be used by the states:
</p>
<pre class="programlisting">
class watch_state;
class watch_access
{
 public:
  virtual void change_state_to(
     watch_state* new_state) = 0;
 protected:
  ~watch_access() {}
};
</pre>
<p>
This interface is realized in the context and each state is given a reference to it. A state can now make a transition by invoking <tt>change_state_to()</tt>. Now, I deliberately didn't write exactly how the context shall implement the interface. From a design and usability perspective public inheritance isn't a good idea; <tt>watch_access</tt> is a result of our implementation efforts of weakening the dependencies and we really don't want to expose implementation details to clients of the <tt>stop_watch</tt>.
</p>
<p>
The perhaps simplest solution is offered by the idiom Private Interface [<a href="#3">3</a>]. All there is to it is to let <tt>stop_watch</tt> inherit <tt>watch_access</tt> privately. Now a conversion from <tt>stop_watch</tt> to <tt>watch_access</tt> is only allowed within the <tt>stop_watch</tt> itself. That is, the <tt>stop_watch</tt> can grant controlled access to its states and clients are shielded from the <tt>watch_access</tt> interface. Or are they really? Well, they are shielded from the conceptual overhead of the interface but there's more to it.
</p>
<p>
What worries me is that inheritance, private or not, puts strong compile-time dependencies upon the clients of <tt>stop_watch</tt>. In his classic book <em>Effective C++</em>, Scott Meyers advices us to &quot;use private inheritance judiciously&quot; [<a href="#2">2</a>]. Meyers also proposes an alternative that I find more attractive, albeit with increased complexity: declare a private nested class in the context and let this class inherit publicly. The context now uses composition to hold an instance of this class as illustrated in Figure 2. Not only is it cleaner with respect to encapsulation, it also allows us to control the compilation dependencies of our clients as it is possible to refactor it to a Pimpl [<a href="#8">8</a>] solution if needed.
</p>
<table class="sidebartable"><tr><td>
<img src="/content/images/journals/ol73/ObjectStates2.gif" width="620" height="148" border="0" alt="An instance of the class" />
</td></tr><tr><td class="title">Figure 2</td></tr></table>

<p>
Enough of fancy diagrams - let's carve it out in code..
</p>
<pre class="programlisting">
class stop_watch
{
 public:
  ...
 private:
  // Meyers Item 39: Prefer public inheritance
  // plus composition in favour of private inheritance.
  class state_controller : public watch_access
  {
    ...
    public:
      ...
      virtual void change_state_to(
         watch_state* new_state)
      {
         ...
      }
    };
    state_controller state;
};
</pre>
<p>
With the main structure of the context in place, we're ready to tackle the allocation of states.
</p>
<h2>
A dynamic allocation scheme
</h2>
<p>
Our first approach is to allocate the states dynamically as they are needed. A state transition simply means allocating the new state, wrapped in a suitable smart pointer from boost [<a href="#4">4</a>], and passing it to the context. Here's an example on the <tt>stopped-state</tt>:
</p>
<pre class="programlisting">
  // watch_state.h
...
typedef boost::shared_ptr&lt;watch_state&gt;
watch_state_ptr;
// stopped_state.cpp
void stopped_state::start(watch_access&amp; watch)
{
   watch_state_ptr started(new started_state);

   watch.change_state_to(started);
}
</pre>
<p>
The started-state has an identical mechanism, but of course it allocates <tt>stopped_state</tt> as its successor. With the allocation scheme in place we can implement the context, shown in Listing 1, overleaf.
</p>
<table class="sidebartable"><tr><td>
<pre class="programlisting">
  // stop_watch.h
class stop_watch
{
 public:
  stop_watch();
  void start();
  void stop();
 private:
  class state_controller : public watch_access
  {
      watch_state_ptr current_state;
    public:
      state_controller(
        watch_state_ptr initial_state)
        : current_state(initial_state)
      {
      }
      // Hide the extra indirection for the
      // client by using en masse delegation.
      watch_state_ptr operator-&gt;() const
      {
         return current_state;
      }
      virtual void change_state_to(
         watch_state_ptr new_state)
      {
         current_state = new_state;
      }
    };

  state_controller state;
  };
</pre>
</td></tr><tr><td class="title">Listing 1</td></tr></table>

<p>
Here we let the <tt>stop_watch</tt> specify its initial state upon construction:
</p>
<pre class="programlisting">
// stop_watch.cpp
stop_watch::stop_watch()
  : state(watch_state_ptr(new stopped_state))
{
}
</pre>
<p>
Our preference of public inheritance in combination with composition over private inheritance leads to an extra level of indirection. We can hide this indirection by overloading <tt>operator-&gt;</tt> in the <tt>state_controller</tt>, which makes the context's delegation to the states straightforward:
</p>
<pre class="programlisting">
// stop_watch.cpp
void stop_watch::start()
{
  state-&gt;start(state);
}
void stop_watch::stop()
{
  state-&gt;stop(state);
}
</pre>
<p>
Dynamic allocation of the states is a simple solution, yet it makes several tradeoffs:
</p>
<table border="0"
style="background-color: rgb(238, 238, 238);"
cellpadding="2" cellspacing="2">
<tr>
<td>+</td>
<td>Allows for stateful states, i.e. instance variables in the
states.</td>
</tr>
<tr>
<td>-</td>
<td>Potentially many and frequent heap allocations may have
negative performance impact.</td>
</tr>
<tr>
<td>-</td>
<td>Hard to change to sharing states (such a change ripples
through all states).</td>
</tr>
<tr>
<td>-</td>
<td>Dependent upon a concrete class (i.e. the next state), which
is a barrier to unit tests</td>
</tr>
</table>
<h2>
Sharing states - the return of the Singletons
</h2>
<p>
With instance variables in the states, dynamic allocation is a simple solution. However, in most applications of Objects for States the state-objects are there just to provide a unique type and do not need any instance variables. <em>Design Patterns</em> describes this as &quot;If State objects have no instance variables [...] then contexts can share a State object&quot; [<a href="#1">1</a>]. In their sample code, <em>Design Patterns</em> notes that this is the case; only one instance of each state-object is required, and with that motivation makes each state a Singleton.
</p>
<p>
After my interview with Mr Singleton I promised to explain why this is the wrong abstraction. The reason is that the responsibility of managing state-instances is put on the wrong object, namely the state itself, and an object should better not assume anything about the context in which it is used. <em>Design Patterns</em> describes a particular case where only one instance is needed. This need, however, doesn't imply a uniqueness constraint on the state-objects themselves that would motivate the Singletons. Further, whether states should be shared or not should be decided in the context. Obviously the Singleton approach breaks this rule and, for all practical purposes, forces all states to be stateless.
</p>
<p>
To summarize, Singleton leads to:
</p>
<ol type="1">
<li>an erroneous abstraction, </li>
<li>unnecessary code complexity, </li>
<li>superfluous uniqueness constraints,</li>
<li>and it seriously limits unit testing capabilities.</li>
</ol>
<p>
Clearly another approach would be preferable. However, before sharing any states, I would like to point to Joshua Kerievsky's advice that &quot;it's always best to add state-sharing code after your users experience system delays and a profiler points you to the state-instantiation code as a prime bottleneck&quot; [<a href="#5">5</a>].
</p>
<h2>
Going global
</h2>
<p>
When implementing Objects for States the uniqueness constraint of Singleton is actually an unwanted by-product of the solution. So, let's focus on the second part of Singleton's intent: &quot;provide a global point of access&quot; [<a href="#1">1</a>]. These are the things programmers speak low about - nobody wants to get caught using globals, yet global variables are more honest about the intent than to camouflage them as Singletons. Consider the following code snippet:
</p>
<pre class="programlisting">
// possible_states.h
class watch_state;
namespace possible_states{
extern watch_state* stopped;
extern watch_state* started;
}
// stopped_state.cpp
#include &quot;possible_states.h&quot;
void stopped_state::start(watch_access&amp; watch)
{
   using possible_states::started;

   watch.change_state_to(started);
}
</pre>
<p>
No constraints on the number of possible instances in the states themselves. But who defines them? The context seems like a good candidate:
</p>
<pre class="programlisting">
// stop_watch.cpp
namespace{
stopped_state stopped_instance;
started_state started_instance;
}
namespace possible_states{
watch_state* stopped = &amp;stopped_instance;
watch_state* started = &amp;started_instance;
}
</pre>
<p>
Except for the construction (we have to initialize our <tt>state_controller</tt> with <tt>possible_states::stopped</tt> instead of a dynamically allocated state), the rest of the context code stays the same. Any tradeoffs made? Yes, always. Here they are:</p>
<table border="0"
style="background-color: rgb(238, 238, 238);"
cellpadding="2" cellspacing="2">
<tr>
<td style="vertical-align: top;">+</td>
<td style="vertical-align: top;">Conceptually simple and
definitely simpler than the classic Singleton
approach (same characteristics, but more honest in its intent).</td>
</tr>
<tr>
<td style="vertical-align: top;">+</td>
<td style="vertical-align: top;">No dependencies from the states
upon concrete classes (only a forward declaration is actually used in <tt>possible_states.h</tt>).</td>
</tr>
<tr>
<td style="vertical-align: top;">+</td>
<td style="vertical-align: top;">Primitive but possible way to
unit test individual states by use of
link-time polymorphism (this technique uses the linker to link in
different state definitions, i.e. test-stubs, instead of the real ones in <tt>stop_watch.cpp</tt>).</td>
</tr>
<tr>
<td style="vertical-align: top;">+-</td>
<td style="vertical-align: top;">States are shared.</td>
</tr>
<tr>
<td style="vertical-align: top;">-</td>
<td style="vertical-align: top;">Forced to share states, which
makes it virtually impossible to use stateful states.</td>
</tr>
<tr>
<td style="vertical-align: top;">-</td>
<td style="vertical-align: top;">Still not quite true to the
â€˜program to an interfaceâ€™ principle.</td>
</tr>
<tr>
<td style="vertical-align: top;">-</td>
<td style="vertical-align: top;">Scalability problems with
<tt>possible_states.h</tt>, which must be updated each time a state is added or
removed.</td>
</tr>
</table>
<h2>
In control
</h2>
<p>
Using link-time polymorphism to unit test? Yuck! Not particularly OO, is it? No, it sure isn't, but I wouldn't discard a solution just by that objection. Anyway, what about finally approaching a solution that removes the dependencies between the sub-states? Moving the state management into the <tt>state_controller</tt> makes it possible.
</p>
<pre class="programlisting">
// watch_access.h
class watch_access
{
public:
   virtual void change_to_started() = 0;
   virtual void change_to_stopped() = 0;
 ...
};

// stop_watch.h
class stop_watch
{
  ...

  class state_controller : public watch_access
  {
      started_state started;
      stopped_state stopped;

      watch_state* current_state;
    public:
      state_controller()
         : current_state(&amp;stopped)
      {
      }
      virtual void change_to_started()
      {
         current_state = &amp;started;
      }

      virtual void change_to_stopped()
      {
         current_state = &amp;stopped;
      }

      ...
    };
  ...
};
</pre>
<p>
The <tt>state_controller</tt> allocates all possible states and switches between them as requested by the states. What's left to the states is specifying their successors in abstract terms:
</p>
<pre class="programlisting">
// stopped_state.cpp
void stopped_state::start(watch_access&amp; watch)
{
   watch.change_to_started();
}
// started_state.cpp
void started_state::stop(watch_access&amp; watch)
{
   watch.change_to_stopped();
</pre>
<p>
}
</p>
<p>
And here we are, finally programming to an interface and not an implementation. Let's look at the resulting context:
</p>
<table border="0"
style="background-color: rgb(238, 238, 238);"
cellpadding="2" cellspacing="2">
<tr>
<td style="vertical-align: top;">+</td>
<td>The responsibility for the allocation scheme is where it
should be: in the context.</td>
</tr>
<tr>
<td style="vertical-align: top;">+</td>
<td>States are easily shared among instances by making them
static. Such
a decision is taken in the context and not coded into the states
themselves as in the traditional Singleton approach.</td>
</tr>
<tr>
<td style="vertical-align: top;">+</td>
<td>All states written towards an interface, which make them easy
to unit test.</td>
</tr>
<tr>
<td style="vertical-align: top;">-</td>
<td>Doesnâ€™t scale well. <tt>watch_access</tt> runs the risk
of growing fat as it has to provide methods for all possible states, which is a similar problem to the global approach with
<tt>possible_states.h</tt>.</td>
</tr>
</table>
<h2>
A generative approach
</h2>
<p>
The previous solution indicated potential scalability problems; adding new states requires modifications to <tt>watch_access</tt> and its implementer, <tt>state_controller</tt>. In my experience this has been an acceptable trade-off for most cases; as long as the state-machine is stable and relatively few states are used (5 - 10 unique states) I wouldn't think twice about it. However, in the ideal world, introducing a new state should only affect the states that need transitions to it. Reflecting upon our last example, although limited to only two states, the pattern is clear: the different methods for changing state (change_to_started(), change_to_stopped()) are identical except for the type encoded in the function name. Sounds like a clear candidate for compile-time polymorphism. The core idea is simple: each state instantiates a member function template with the next state as argument.
</p>
<pre class="programlisting">
// Example from stopped_state.h
void stopped_state::start(watch_access&amp; watch)
{
   watch.change_state_to&lt;started_state&gt;();
}

</pre>
<p>
Each member function template instantiation creates the new state object and changes the reference in the context. Something along the lines of:
</p>
<pre class="programlisting">
class X
{
...
   template&lt;class new_state&gt;
   void change_state_to()
   {
      watch_state_ptr created_state(new new_state);

      current_state = created_state;
   }
};
</pre>
<p>
A quick quiz: in the listing above, what class should X be? The states specify their transitions by invoking methods on <tt>watch_access</tt> and by means of the virtual function mechanism the call is dispatched to the context. Now, there's no such beast as virtual member function templates in C++. The solution is to intercept the call chain and capture the template argument in an, necessarily non-virtual, member function template, create the new state instance there and delegate to the context by a virtual function (see Listing 2).
</p>
<table class="sidebartable"><tr><td>
<pre class="programlisting">
// watch_access.h
class watch_access
{
public:
   template&lt;class new_state&gt;
   void change_state_to()
   {
      watch_state_ptr created_state(new new_state);

      change_state_to(created_state);
   }
protected:
   ~watch_access() {}
   typedef boost::shared_ptr&lt;watch_state&gt;
      watch_state_ptr;
private:
   // Delegate the actual state management to the
   // derived class through this method.
   virtual void change_state_to(
      watch_state_ptr new_state) = 0;
};
// stop_watch.h
class state_controller : public watch_access
{
   watch_state_ptr current_state;
 public:
   state_controller()
   {
     // Specify the initial state.
     watch_access::change_state_to&lt;stopped_state&gt;();
   }
   virtual void change_state_to(
      watch_state_ptr new_state)
   {
      current_state = new_state;
   }
   ...
};
</pre>
</td></tr><tr><td class="title">Listing 2</td></tr></table>
<p>
Considering the tradeoffs shows that the one step forward in scalability pushed us back with respect to dependency management:</p>
<table border="0"
style="background-color: rgb(238, 238, 238);"
cellpadding="2" cellspacing="2">
<tr>
<td style="vertical-align: top;">+</td>
<td style="vertical-align: top;">Scales well, no know-them-all
class; the compiler generates code to instantiate states.</td>
</tr>
<tr>
<td style="vertical-align: top;">-</td>
<td style="vertical-align: top;">The states depend upon concrete
classes</td>
</tr>
</table>
<h2>
Recycling states
</h2>
<p>
The last example brought us back to a dynamic allocation scheme. However, that knowledge is encapsulated within <tt>watch_access</tt> and we can easily switch to another allocation strategy. For example, in a single-threaded context static objects are a straightforward way to share states and avoid frequent allocations:
</p>
<pre class="programlisting">
// watch_access.h
class watch_access
{
public:
   template&lt;class new_state&gt;
   void change_state_to()
   {
      static new_state created_state;

      change_state_to(&amp;created_state);
   }
   ...
};
</pre>
<p>
State objects can also be recycled by introducing a variation of the design pattern Flyweight [<a href="#1">1</a>]. In fact, <em>Design Patterns</em> links these two patterns together with its statement that &quot;it's often best to implement State [...] objects as flyweights&quot;. Does the claim hold true? Let's try it out and see.
</p>
<p>
First each object is associated with a unique key. The idea is, that the first time an object is requested from the flyweight factory, a look-up is performed. If an object with the requested key already exists a pointer to that object is returned. Otherwise the object is created, stored in the factory, and a pointer to the newly created object returned. The example below introduces a pool for state objects in a <tt>flyweight_factory</tt> using the unique type-name as key (Listing 3).
</p>
<table class="sidebartable"><tr><td>
<pre class="programlisting">
template&lt;class flyweight&gt;
class flyweight_factory
{
public:
   typedef boost::shared_ptr&lt;flyweight&gt;
    flyweight_ptr;
   template&lt;class concrete_flyweight&gt;
   flyweight_ptr get_flyweight()
   {
      const std::string key(
       typeid(concrete_flyweight).name());

      typename pool_type::const_iterator
       existing_flyweight(pool.find(key));

      if(pool.end() != existing_flyweight) {
         return existing_flyweight-&gt;second;
      }
      else {
         flyweight_ptr new_flyweight(
          new concrete_flyweight);

         const bool inserted = pool.insert(
          std::make_pair(key, new_flyweight)).second;
         assert(inserted);

         return new_flyweight;
      }
   }
private:
   typedef std::map&lt;std::string, flyweight_ptr&gt;
    pool_type;
   pool_type pool;
};
</pre>
</td></tr><tr><td class="title">Listing 3</td></tr></table>
<p>
The flyweights are fetched from the instantiations of the member function template in <tt>watch_access</tt> (Listing 4).
</p>
<table class="sidebartable"><tr><td>
<pre class="programlisting">
class watch_access
{
   typedef flyweight_factory&lt;watch_state&gt;
    state_factory;
   state_factory factory;

public:
   template&lt;class new_state&gt;
   void change_state_to()
   {
     change_state_to(
      factory.get_flyweight&lt;new_state&gt;());
   }
   protected:
   ~watch_access() {}

  typedef state_factory::flyweight_ptr
   watch_state_ptr;
private:
   // Delegate the actual state management to the
derived
  // class through this method.
   virtual void change_state_to(
   watch_state_ptr new_state) = 0;
};
</pre>
</td></tr><tr><td class="title">Listing 4</td></tr></table>
<p>
The state_controller stays as before because the internal protocol, <tt>change_state_to(watch_state_ptr)</tt>, is left untouched:
</p>
<p>
</p>
<table border="0"
style="background-color: rgb(238, 238, 238);"
cellpadding="2" cellspacing="2">
<tr>
<td style="vertical-align: top;">+</td>
<td style="vertical-align: top;">Scales well, no know-them-all
class; the compiler generates code to instantiate states.</td>
</tr>
<tr>
<td style="vertical-align: top;">+</td>
<td style="vertical-align: top;">Allows for sharing states among
all instances of stop_watch by making the <tt>flyweight_factory</tt> static in <tt>watch_access</tt>.</td>
</tr>
<tr>
<td style="vertical-align: top;">+</td>
<td style="vertical-align: top;">Generic <tt>flyweight_factory</tt> for
all default-constructable types.</td>
</tr>
<tr>
<td style="vertical-align: top;">-</td>
<td style="vertical-align: top;">The states depend upon concrete
classes.</td>
</tr>
<tr>
<td style="vertical-align: top;">-</td>
<td style="vertical-align: top;">Relatively high design complexity</td>
</tr>
</table>
<h2>
Conclusion
</h2>
<p>
As this article has highlighted the problems inherent in a Singleton based Objects for States solution, it feels fair to let Mr Singleton get the final word. After all, if I was successful his career may suffer. Will the two patterns finally be separated?
</p>
<blockquote>
<p>
<b>&quot;I sure hope so&quot;</b>, Mr Singleton answers, <b>&quot;Clearly there are better alternatives and if I ever get the opportunity I'm prepared to sacrifice my link in Objects for States in the name of good design.&quot;</b>
</p>
<p>
&quot;That's a great attitude and I'm delighted you take it that way. Speaking of design, any particular solution you would recommend?&quot;
</p>
<p>
<b>&quot;I don't think you can put it that way. Like all design alternatives each one of them comes with its own set of tradeoffs, which must be carefully balanced depending on the problem at hand.&quot;</b>
</p>
</blockquote>
<h2>
References
</h2>
<p class="biblomixed">[<a name="1">1</a>] Gamma, Helm, Johnson &amp; Vlissides, <em>Design Patterns</em>, Addison-Wesley, 1995</p>
<p class="biblomixed">[<a name="2">2</a>] Scott Meyers, <em>Effective C++ Third Edition</em>, Addison-Wesley, 2005</p>
<p class="biblomixed">[<a name="3">3</a>] James Newkirk, <em>Private interface</em>, 1997, <a href="http://www.objectmentor.com/">http://www.objectmentor.com/</p></a>
<p class="biblomixed">[<a name="4">4</a>] <a href="http://www.boost.org">http://www.boost.org</p></a>
<p class="biblomixed">[<a name="5">5</a>] Joshua Kerievsky, <em>Refactoring to Patterns</em>, Addison-Wesley, 2004</p>
<p class="biblomixed">[<a name="6">6</a>] Mark Radford, `SINGLETON - The Anti-Pattern!', Overload 57</p>
<p class="biblomixed">[<a name="7">7</a>] The complete source code for this article: www.adampetersen.se</p>
<p class="biblomixed">[<a name="8">8</a>] Herb Sutter, <em>Exceptional C++</em>, Addison-Wesley, 2000</p>
<p>
The Pimpl idiom was originally described by John Carolan as the &quot;Cheshire Cat&quot;.
</p>
<p class="biblomixed">[<a name="9">9</a>] John Vlissides, <em>Pattern Hatching</em>, Addison-Wesley, 1998</p>
<p class="biblomixed">[<a name="10">10</a>] Meyers &amp; Alexandrescu, `C++ and the Perils of Double-Checked Locking', 2004, <a href="http://www.aristeia.com/">http://www.aristeia.com/</p></a>
</ol>
<h2>
Acknowledgements
</h2>
<p>
I would like to thank Drago Krznaric, Alan Griffiths, Phil Bass, and Richard Blundell for their valuable feedback.
</p>

<p>
All of the code for this article is available from my website: <a href="http://www.adampetersen.se">http://www.adampetersen.se</a>
</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
