    <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  :: The State Pattern - A New Implementation</title>
        <link>https://members.accu.org/index.php/journals/528</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 #33 - Aug 1999 + 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/c171/">33</a>
                    (8)
<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/c171-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c171+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;The State Pattern - A New Implementation</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 August 1999 17:50:54 +01:00 or Thu, 26 August 1999 17:50:54 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="article" lang="en">
<div class="titlepage">
<div>
<div>
<h2><a name="d0e1" id="d0e1"></a>The State Pattern -
A New Implementation</h2>
</div>
<div class="author">
<h3><span class="firstname">Phil</span> <span class=
"surname">Bass</span></h3>
<tt class="email">&lt;<a href=
"mailto:phil@stoneymanor.demon.co.uk">phil@stoneymanor.demon.co.uk</a>&gt;</tt></div>
</div>
<hr></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id=
"d0e18"></a>Introduction</h2>
</div>
<p>In their book, <i class="citetitle">Design Patterns, Elements of
Reusable Object-Oriented Software</i>, Gamma, Helm, Johnson and
Vlissides describe a design pattern called <span class=
"bold"><b>State</b></span>. The <span class=
"bold"><b>State</b></span> pattern allows an object to change its
behaviour when its internal state changes.</p>
<p>For example, suppose we have a Button class with a (public)
member function, Press(). The first time the Press() function is
called some piece of equipment is turned on; the second time the
equipment is turned off. There is one event (pressing the button)
that triggers multiple actions (switch on, switch off).</p>
<p>Gamma, et al. (the Gang of Four), present a design in which each
internal state is a separate object. The parent class stores a
pointer to the current state object and delegates all operations to
the current state. The states are polymorphic. The base class
declares a virtual function to handle each event and derived
classes provide different implementations of the event handling
functions.</p>
<pre class="programlisting">
class Button;

class State
{
public:
    virtual void Toggle(Button&amp;);
};

class Off : public State
{
public:
    virtual void Toggle(Button&amp;);
};

class On : public State
{
public:
    virtual void Toggle(Button&amp;);
};

class Button
{
public:
    Button();
    void Press() {state-&gt;Toggle(*this);}
private:
    State* state;
};
</pre>
<p>Figure 1 - State selects and performs action</p>
<p>The parent class passes a reference to itself to each of the
event handling functions so that the current state can be updated.
The Design Patterns book makes the State base class a friend and
its derived classes call a protected function in State to get
access to the state pointer. The implementation must also consider
when the state objects are created and destroyed and where they are
stored.</p>
<p>This article presents an alternative implementation in which the
derived classes, passing a reference to the parent class and
friends all become unnecessary. This new implementation tends to be
simpler and fits well with the usual solutions to the problems of
creating, destroying and accessing the state objects.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e44" id="d0e44"></a>Reducing the
Role of the State Objects</h2>
</div>
<p>In the Gang of Four version the State objects do two things:
they select an action and perform that action on behalf of the
parent object.</p>
<p>In the new implementation the State objects select an action,
but the parent object retains responsibility for performing the
selected action.</p>
<pre class="programlisting">
class Button
{
public:
    Button() : state(&amp;off) {}
    void Press();
private:
    struct State
    {
        void (Button::*toggle)();
    };
private:
    static const State off, on;
private:
    void SwitchOn ();
    void SwitchOff();
private:
    const State* state;
};

const Button::State Button::off = 
                        {&amp;Button::SwitchOn };
const Button::State Button::on  = 
                        {&amp;Button::SwitchOff};

void Button::Press() {(this-&gt;*state-&gt;toggle)();}
</pre>
<p>Figure 2 - State selects action, Button performs action</p>
<p>The State class stores pointers to member functions of the
Button class. When a button press event occurs the Press() function
uses the current state to get a pointer to a Button member function
and executes that function on its own Button object.</p>
<p>If we dissect the Press() function we can break it down into the
following steps:</p>
<pre class="programlisting">
typedef void (Button::*Action)();  
// pointer to Button member function

void Button::Press()
{
    Action action = state-&gt;toggle;  
    // select action
    (this-&gt;*action)();
    // perform selected action
}
</pre>
<p>If the current state is 'off', state-&gt;toggle points to
Button::SwitchOn(), which switches on the equipment and sets the
Button state to 'on'. Now, state-&gt;toggle points to
Button::SwitchOff(), which switches the equipment off again and
resets the Button state to 'off'.</p>
<pre class="programlisting">
void Button::SwitchOn()
{
    // ... switch on the equipment ...
    state = &amp;on;
    // change to the 'on' state
}

void Button::SwitchOff()
{
    // ... switch off the equipment ...
    state = &amp;off;
    // change to the 'off' state
}
</pre>
<p>What could be simpler?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e67" id="d0e67"></a>Analysis</h2>
</div>
<p>The State class only contains data; there are no virtual
functions to override and, hence, no need of derived classes. To
emphasise this I have used a Plain Old Data type (struct) instead
of a class with separate interface and implementation. Purists may
prefer to make the data private and provide suitable access
functions.</p>
<p>Now that there is just one State class instead of a class
hierarchy it can be nested inside the parent class without unduly
complicating the parent class declaration. This generates fewer
identifiers at namespace scope.</p>
<p>The simple, data-only State objects are good candidates for
class scope and static storage. There is no need to use the
Singleton design pattern to provide the action functions with
access to the State objects or to ensure that all Buttons share the
same State information.</p>
<p>The relationships between states, events and actions are fixed
at compile time and stored in the State objects, so the State
objects can be const qualified. The set of State objects provides a
direct implementation of a state table.</p>
<p>This implementation typically produces simpler source code,
especially when the parent class contains data that is shared by
the action functions. The pointer to the current state is just such
a data item. Each action function can change the state of the
parent object by directly updating the pointer.</p>
<p>It may be argued that the State class is very weak. However, it
is private to Button and, as all of its members are pointers to
Button member functions, it is difficult to see how the State
representation could change. So, client code can not misuse the
State class and little would be gained from hiding the data behind
access functions.</p>
<p>The presence of the State class definition within the Button
class is slightly more difficult to defend. In large projects this
style can lead to excessive dependencies between header files and
painfully slow compilations. However, if this is a problem, it can
be fixed by storing pointers to the State objects in the Button
class instead of the objects themselves. The State class definition
can then be moved to the Button's .cpp file, leaving just a
declaration of the incomplete type in the header.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e84" id="d0e84"></a>Conclusion</h2>
</div>
<p>The implementation described in <i class="citetitle">Design
Patterns</i> uses fully-fledged State objects. Encapsulation,
inheritance and polymorphism are all essential to their design. Of
course, the Gang of Four were writing a book about object-oriented
design patterns in general and pointers to member functions may not
be available in other OO languages. In the context of C++, however,
I believe applying object-oriented principles too rigidly has led
to an inappropriate separation of responsibilities. Like all good
things, object-oriented thinking can be overdone.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
