    <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  :: Factories in C++: Disposing of the Product</title>
        <link>https://members.accu.org/index.php/journals/556</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 #31 - Apr 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/c173/">31</a>
                    (10)
<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/c173-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c173+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;Factories in C++: Disposing of the Product</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 April 1999 17:50:52 +01:00 or Mon, 26 April 1999 17:50:52 +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>Introduction</h2>
</div>
<p>In the section of <i class="citetitle">Design Patterns</i>
[<a href="#GoF">GoF</a>] titled &quot;Creational Patterns&quot;, four
patterns based directly on the factory concept are documented.
These are <i class="firstterm">Abstract Factory</i>, <i class=
"firstterm">Factory Method</i>, <i class="firstterm">Builder</i>
and <i class="firstterm">Prototype</i>. While the book documents a
number of issues relating to these patterns, the list given is far
from exhaustive. One significant omission is that (as far as I can
see) only the issues to do with creating objects are considered,
without regard to how they are disposed of. This is important,
given that one purpose of a factory is to encapsulate the creation
mechanism.</p>
<p>I've been giving this problem a lot of thought recently, and in
this article I would like to present the ideas I've come up with.
Please read critically! I am very interested in hearing about other
peoples' ideas on this topic too.</p>
<p>In this article I refer simply to <i class="firstterm">factory
patterns</i>, or even more simply, <i class=
"firstterm">factories</i>. I don't believe it is useful to talk
about on specific factory patterns, because individual patterns do
not occur in isolation in software design. These is too much
overlap to make it worth while treating any factory pattern
individually. This is inevitable because design patterns are not
themselves designs. Rather, they represent approaches to solving
certain problems. Further, some design patterns use other design
patterns, often with the former specialising the latter. For
example (as John Vlissides points out in <i class=
"citetitle">Pattern Hatching</i> [<a href=
"#Vlissides">Vlissides</a>]) the <i class="firstterm">Abstract
Factory</i> pattern uses the <i class="firstterm">Factory
Method</i> pattern.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e63" id="d0e63"></a>Example Class
Hierarchy</h2>
</div>
<p>Before continuing, we need an example to work with. Consider a
GUI multi-document system, which supports a Word Processor,
Database, Spreadsheet etc., where the document classes have a
common ABC called <tt class="classname">Doc</tt>. This is a very
common example but I feel it works well in these situations. The
following UML diagram shows the class hierarchy (only the word
processor and database are included, for simplicity):</p>
<div class="c2"><img src="/var/uploads/journals/resources/Radford%20factories%201.png"
align="middle"></div>
<p>There will be a corresponding view hierarchy:</p>
<div class="c2"><img src="/var/uploads/journals/resources/Radford%20factories%202.png"
align="middle"></div>
<p>In addition there will be a requirement for some method of
viewing and updating the properties of each document. This is
normally done using a popup dialog box in a GUI system. Here the
properties will be abstracted as a class called <tt class=
"classname">PropertiesUI</tt>. This leads to the following
hierarchy:</p>
<div class="c2"><img src="/var/uploads/journals/resources/Radford%20factories%203.png"
align="middle"></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e81" id="d0e81"></a>Disposal</h2>
</div>
<p>Before proceeding with the task of suggesting a solution to the
disposal problem, I would like to make a couple of observations
regarding the C++ programming language in this context.</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>In C++ the burden of deletion of objects rests with the
programmer (in some other languages such as Java for example, it is
not a problem because garbage collection takes care of things).
This means our design must provide a means of disposing of the
objects created by a factory.</p>
</li>
<li>
<p>C++ provides several ways to allocate memory for objects
(automatic, static, plus more than one way to allocate dynamically
on the heap). Since the exact creation mechanism is encapsulated
within the factory, clients can not make any assumptions about the
mechanism of disposal.</p>
</li>
</ol>
</div>
<p>The approach used in the <i class="citetitle">Design
Patterns</i> C++ examples is to assume that objects were created
using <tt class="literal">new</tt>, so clients must use <tt class=
"literal">delete</tt>. In reality, it is dangerous to place this
burden on the client, because it exposes the creation mechanism,
the encapsulation of which is a purpose of the factory. Also,
consider the following two techniques in which the usual form of
<tt class="literal">new</tt> is not used (at least, not
directly):</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>The factory may use pre-allocated memory, constructing its
objects using the placement form of <tt class=
"literal">new</tt>.</p>
</li>
<li>
<p>Sometimes the factory may avoid the overhead of creating new
objects, by recycling objects previously disposed of.</p>
</li>
</ol>
</div>
<p>I would like to continue by discussing two possible solutions to
the disposal problem:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><span class="emphasis"><em>Disposal by the factory</em></span>:
in this solution the object is passed back to the factory for
disposal.</p>
</li>
<li>
<p><span class="emphasis"><em>Use a handle</em></span>: in this
solution, rather than return a pointer, the factory returns a
handle (or proxy) to the object.</p>
</li>
</ol>
</div>
<p>These solutions all have points for and against them. As usual
there is no single best option; it all comes down to the individual
design criteria.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e132" id="d0e132"></a>Disposal by
the Factory</h2>
</div>
<p>In my experience, this is the most frequently quoted solution is
to simply pass the object back to the factory. After all, the
factory knows how to dispose of what it created, having provided
the creation mechanism. However, things are not quite that simple,
as in OO systems it is unlikely that the concrete class will be
known for very long following object creation. Knowing which type
of factory to pass it to for disposal may not be possible without
first going through a type-laundering process. If the need for type
laundering is to be avoided, then the deletion mechanism must be
the same for each type of concrete class. In other words, this
solution forces each type of factory to use the same creation
mechanism. This may or may not be acceptable; it's a decision
required at the design stage.</p>
<p>There is a further problem with this solution: the factory must
be available at disposal time. This is not usually a problem with
factories following the Abstract Factory design pattern, as the
factory is an object in its own right. However, if the factory was
of a type following the <i class="firstterm">Factory Method</i> or
<i class="firstterm">Prototype</i> design patterns, the 'baggage'
the object providing the factory function brings with it may make
this difficult.</p>
<p>I do not intend to take this any further in this article as it
depends heavily on the type of factory in use.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e147" id="d0e147"></a>Use a
Handle</h2>
</div>
<p>Another solution is not to return the object directly but to
return a handle to it. If the factory uses the simple form of
<tt class="literal">new</tt> to create its product, the handle it
returns can be <tt class="classname">std::auto_ptr</tt>. This has
the downside is that it is difficult to manage more than one
reference to the object simultaneously.</p>
<p>If the factory employs any of the creation techniques described
above, then a proprietary handle is needed. Using a proprietary
handle has the advantage that it allows a close coupling with the
factory. In other words, the handle can have an intimate knowledge
of the creation mechanism used by the factory. I propose to
generalise the handle in the form of a 'smart pointer' and to start
with the following sketch of a design for it.</p>
<pre class="programlisting">
template &lt;typename ProductType&gt;
class ProductPtr
{
  ProductType* product;
public:
  ProductPtr(ProductType* inputProduct)
  : product(inputProduct) {}

  ~ProductPtr() { delete product; }

  ProductType* operator-&gt;() const
  { return product; }
};
</pre>
<p>Remember, here we are concerned purely with the problem of the
mechanism of disposing of the product. This is my excuse for
leaving things like assignment and copy construction out of the
above class, and ignoring issues like managing ownership &#9786;.
Whether or not more than one handle to the same object is allowed
or not is, in my view at least, a separate design decision.
Ownership determines whether or not the handle should disose of the
object, not how it should do so.</p>
<p>So far, we have a similar situation to simply using <tt class=
"classname">std::auto_ptr</tt>. The problem now, is to give
<tt class="classname">ProductPtr</tt> knowledge of the disposal
mechanism. We can not actually code this mechanism in <tt class=
"classname">ProductPtr</tt>, because we would end up with the same
problem as we have when passing objects back to the factory for
disposal. The <i class="firstterm">Strategy</i> design pattern can
be used to solve this problem. Going back to the <tt class=
"classname">Doc</tt>, <tt class="classname">View</tt> and
<tt class="classname">PropertiesUI</tt> classes above, let us
introduce the following ABC.</p>
<pre class="programlisting">
class DisposalMechanism
{
public:
  virtual void operator() (
    void* disposee) const = 0;
};
</pre>
<p>Now we derive the following:</p>
<pre class="programlisting">
class BasicDisposalMechanism :
  public DisposalMechanism
{
  BasicDisposalMechanism() {}
  BasicDisposalMechanism(
    BasicDisposalMechanism const&amp;);
  BasicDisposalMechanism &amp;
  operator=(BasicDisposalMechanism const&amp;);

public:
  virtual void
  operator()(void* disposee) const
  { delete disposee; }
  static BasicDisposalMechanism const &amp;
  instance()
  {
    BasicDisposalMechanism inst;
    return inst;
  }
};
</pre>
<p>Then we extend ProductPtr as follows:</p>
<pre class="programlisting">
template &lt;typename ProductType&gt;
class ProductPtr
{
  ProductType* product;
  DisposalMechanism&amp; disposer;
public:
  ProductPtr(
    ProductType* inputProduct,
    DisposalMechanism const&amp; inputDisposer)
    : product(inputProduct),
      disposer(inputDisposer)
  {}

  ~ProductPtr() { disposer(product); }

  ProductType* operator-&gt;() const
  { return product; }
};
</pre></div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e197" id="d0e197"></a>References</h2>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] <span class="citetitle"><i class=
"citetitle">Design Patterns: Elements of Reusable Object-Oriented
Software</i></span>, Gamma, Helm, Johnson &amp; Vlissides,
Addison-Wesley.</p>
</div>
<div class="bibliomixed"><a name="Coplien" id="Coplien"></a>
<p class="bibliomixed">[Coplien] <span class="citetitle"><i class=
"citetitle">Advanced C++ Programming Styles and Idioms</i></span>,
James O. Coplien, Addison-Wesley.</p>
</div>
<div class="bibliomixed"><a name="Vlissides" id="Vlissides"></a>
<p class="bibliomixed">[Vlissides] <span class=
"citetitle"><i class="citetitle">Pattern Hatching: Design Patterns
Applied</i></span>, John Vlissides, Addison-Wesley.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
