    <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  :: Patterns - The Abstract Factory</title>
        <link>https://members.accu.org/index.php/journals/550</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 #30 - Feb 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/c174/">30</a>
                    (11)
<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/c174-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c174+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;Patterns - The Abstract Factory</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 February 1999 16:50:52 +00:00 or Fri, 26 February 1999 16:50:52 +00: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>Let me remind you that my purpose in writing these articles is
to try to broaden my understanding, both by having to make the
effort to express myself and from the resulting corrections from
readers. I am doing my part, are you doing yours?</p>
<p>I had just finished a thoughtful reread of the section of the
GoF's <i class="citetitle">Design Patterns</i> on the <span class=
"emphasis"><em>Abstract Factory</em></span> pattern (well actually
I started by reading the <span class=
"emphasis"><em>Bridge</em></span> pattern but that referred to
<span class="emphasis"><em>Abstract Factory</em></span> which led
me to study that) when I had to go to cook the supper. It doesn't
take much intellectual effort to slice carrots so I continued to
think about what I had read and how I might present it for your
edification.</p>
<p>I thought about my 'motherboard' example but as I thought round
the problem it became clear that it was rather too complicated for
what I wanted. Next I thought about the Christmas presents my wife
had received. Among those were some electrical tools. Those seemed
a little too simple (drill bits are reasonably portable between
different manufacturers.)</p>
<p>Finally my eyes fell on the food-mixer and I realised that this
was just what I wanted.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e40" id="d0e40"></a>Modelling a
Food-mixer</h2>
</div>
<p>Each manufacturer has their own specific food-mixer tool with an
entire range of add-ons. It is no good buying a bean slicer from
one manufacturer and trying to plug it into another manufacturer's
base unit. In addition there are free-standing bean slicers.</p>
<p>Let us focus on bean slicers for a moment. Clearly we have a
perfectly good abstraction. You feed beans in and sliced beans come
out - providing you have supplied an appropriate power supply. The
bean slicer will need cleaning, resharpening etc. If you want to
slice some beans you probably do not care what slicer is used. In
general you will not line up half a dozen different slicers and
then choose one; you will use the one you have got. In other words
you will have an instance of some concrete class derived from the
abstraction 'BeanSlicer'.</p>
<p>Some of those concrete classes will be add-on tools for a
food-mixer. FoodMixer will be another abstraction. In your kitchen
you may have an instance of a concrete type derived from the
abstraction 'BeanSlicer' that has nothing to do with your
food-mixer. In other words the concept of a bean slicer is
completely independent of the concept of a food-mixer.</p>
<p>Consider the following conversation:</p>
<div class="variablelist">
<dl>
<dt><span class="term">Customer:</span></dt>
<dd>
<p>I would like to buy a bean slicer.</p>
</dd>
<dt><span class="term">Sales Person:</span></dt>
<dd>
<p>Do you have any particular one in mind?</p>
</dd>
<dt><span class="term">C:</span></dt>
<dd>
<p>One that will attach to my food mixer.</p>
</dd>
<dt><span class="term">SP:</span></dt>
<dd>
<p>What kind of food-mixer do you have?</p>
</dd>
<dt><span class="term">C:</span></dt>
<dd>
<p>One of those made by XYZ.</p>
</dd>
<dt><span class="term">SP:</span></dt>
<dd>
<p>Do you know which model?</p>
</dd>
</dl>
</div>
<p>etc.</p>
<p>The purpose of the dialogue is to establish exactly which type
of bean slicer the customer wants. At the conclusion the customer
will go away with a bean slicer that was made for his/her
food-mixer.</p>
<p>How can we represent these ideas in software?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e94" id="d0e94"></a>Start with
Abstractions</h2>
</div>
<p>First we will need to create abstract base classes to represent
all the different types of kitchen tool that might be attached to
our abstract concept of a food-mixer (itself a kitchen tool). It
will be useful to be as complete as possible because that will
ensure that our code will be stable and not repeatedly force
recompilation of application code. Typically we might write:</p>
<pre class="programlisting">
class KitchenTool
{
public:
  KitchenTool(){};
  // this is a base class designed for 
  // derivation
  virtual ~KitchenTool()throw(){};      
  // can make a new one
  virtual KitchenTool &amp; void clone() = 0; 
  void destroy(){delete this;}
  virtual KitchenTool &amp; clean() = 0;
  virtual KitchenTool &amp; use() = 0;
  virtual KitchenTool &amp; store() = 0;
protected:
  // Must not be publicly copied 
  // (though the clone function 
  KitchenTool(KitchenTool const &amp;){}throw();
private:
  // cannot be assigned, so declare the 
  // following but do not implement
  virtual KitchenTool &amp; operator=
                        (KitchenTool const &amp;);
};
</pre>
<p>Note that I have to define a default constructor because I need
to constrain copy construction by making it <tt class=
"literal">protected</tt> (though, in the absence of data, there is
nothing to do). The latter is necessary because the concept of a
<tt class="classname">KitchenTool</tt> is clearly not something
that should be passed by value. The existence of the clone function
results in a need to have a way of destroying the resulting dynamic
instance.</p>
<p>I think it is clear nonsense to allow default assignment and so
have chosen to make it a non-implemented private function.</p>
<p>I thought about adding a few other member functions but then
decided that I should encapsulate such things as <tt class=
"methodname">attach()</tt> and <tt class="methodname">detach()</tt>
in the more general abstractions of <tt class=
"methodname">use()</tt> and <tt class="methodname">store()</tt>. In
practice I would probably want to do quite a bit more.</p>
<pre class="programlisting">
class Whisk : public KitchenTool
{
public:
  Whisk(){};
  // this is a base class designed for 
  // derivation
  ~Whisk()throw(){};
  // can make a new one
  Whisk &amp; void clone() = 0; 
  void destroy(){delete this;}
  Whisk &amp; clean() = 0;
  Whisk &amp; use() = 0;
  Whisk &amp; store() = 0;
protected:
  // Must not be publicly copied 
  // (though the clone function 
  Whisk(Whisk const &amp;){}throw();
private:
  // cannot be assigned, so declare the 
  // following but do not implement
  virtual Whisk &amp; operator= (Whisk const &amp;);
};
</pre>
<p>You may be surprised by the return types on those overriders for
the virtual functions from the base. However C++ supports covariant
return types exactly to support this kind of thing. Whether your
compiler knows that is another problem entirely.</p>
<p>Note that <tt class="classname">Whisk</tt> is an abstract base
class derived from another abstract base class. You might want to
add some specifically <tt class="classname">Whisk</tt> behaviour at
this stage.</p>
<p>Next let us distinguish between a free standing <tt class=
"classname">Whisk</tt> and one that can be attached (to a
food-mixer). The concept of being attachable seems to be a mixin
type abstraction, so I might add:</p>
<pre class="programlisting">
class Attachable{
public:
  struct Failed {};
  virtual attach(KitchenTool &amp;)throw (Failed) = 0;
  virtual detach(KitchenTool &amp;)throw (Failed) = 0;
protected:
  ~Attachable(){}
};
</pre>
<p>You may be puzzled by that <tt class="literal">protected</tt>
destructor and think I should be providing a <tt class=
"literal">public</tt> <tt class="literal">virtual</tt> one instead.
However anytime you see a <tt class="literal">public</tt>
<tt class="literal">virtual</tt> destructor you should expect to be
able to destroy the object through a pointer of the class type.
That is usually a mistake for a mixin (pure interface) type. Types
that inherit from this mixin will be able to call the destructor,
but we will not be able to publicly destroy these objects through a
pointer to their interface. This is another place where you should
re-examine transmitted wisdom even if you eventually decide to go
along with it.</p>
<p>There is an issue that some of you might like to think about,
and then write in about. Should <tt class=
"classname">Attachable</tt>'s member functions be provided like
that? The process of attachment involves two objects. Perhaps the
functions should be at namespace scope rather than class scope so
that the symmetry of the operation can be catered for. (<tt class=
"methodname">Attach</tt> and <tt class="methodname">detach</tt> are
rather like adding and subtracting - however I would resist any
temptation to provide overloaded operators.)</p>
<p>Now we can write:</p>
<pre class="programlisting">
class AttachableWhisk: 
  public Whisk, 
  public Attachable
{
 // what, if anything, do you think goes here?
}
</pre>
<p>And now I can provide some concrete classes derived from
AttachableWhisk.</p>
<p>I can follow up with similar sub-hierarchies for beaters, pastry
hooks, etc.</p>
<p>Among the entire range of kitchen tools one will be the
food-mixer. This is also provided as an abstraction.</p>
<p>At this stage I might sit down and implement a complete set of
tools from some manufacturer.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e184" id="d0e184"></a>The Wedding
List - The Need for an Abstract Factory</h2>
</div>
<p>Imagine that you are about to get married and that you and your
chosen life partner are sitting down preparing one of those now
traditional list of potential wedding presents. Under the heading
of <span class="emphasis"><em>Kitchen Gadgets</em></span> you list
all the things you would like to have in your kitchen. At some
stage you will need to decide which manufacturer's product line you
are going to ask for. In one way it does not matter as long as you
are consistent in so far as a base unit (food-mixer) and
attachments are concerned.</p>
<p>You can decide what gadgets you want and which manufacturer as
almost independent decisions.</p>
<p>The same should apply in your software. Having decided on the
supplier you should not have to track that decision for each
purchase.</p>
<p>So what we write is an abstract factory class that basically
consists of a large number of abstract factory functions. Something
like:</p>
<pre class="programlisting">
class MakeKitchenTools
{
public:
  virtual FoodMixer * makeFoodMixer() = 0;
  virtual Whisk * makeWhisk() = 0;
// rest of tools
  virtual ~MakeKitchenTools(){};
};
and then provide suitable concrete instances:
class ABCfactory: public MakeKitchenTools
{
public:
  ABCfactory(){}
  FoodMixer * makeFoodMixer() 
  { return new ABCFoodMixer();}
  Whisk * makeWhisk()
  { return new ABCWhisk;}
// rest of tools
  ~ABCfactory(){}
  // default ctor, copy ctor and assignment OK
};
</pre>
<p>Note that <tt class="classname">ABCFoodMixer</tt> etc will be
concrete classes derived from an appropriate base.</p>
<p>Now I can write code such as:</p>
<pre class="programlisting">
int main()
{
  MakeKitchenTools const &amp; toolmaker =
                               new ABCfactory;
  Whisk * whisk = toolmaker.makeWhisk();
  BeanSlicer * beanSlicer = 
                   toolmaker.makeBeanSlicer();
// other code
  whisk-&gt;destroy();
  beanSlicer-&gt;destroy();
};
</pre>
<p>There are many refinements and improvements that could be made
to the above code (I have even deliberately left in a few poor
choices to encourage you to read critically) and I hope that
several of you will feel able to contribute your ideas and
insights. However the fundamental idea is centred on that abstract
factory class that can be used as a base for specific factory
classes. Your program can then use instances of these to make
instances of a range of items that must work consistently
together.</p>
<p>If possible, decisions should only be recorded once in a
program. That means a change will promulgate through the whole
program. We should avoid unnecessary coupling between items. For
example we should avoid coupling a whisk and a food-mixer. However
we do need methods to ensure compatibility between objects. One of
the main tasks of an abstract factory is to provide exactly
that.</p>
<p>Or did I miss the point? &#9786;</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
