Re: Template Method vs Strategy (was: Exceptional C++ Item 23)
Robert Martin wrote:
Template Method and Strategy have the same goal of
implementing a high level algorithm independent of low level
details. TM is easy to build, and light on CPU and Memory,
but is inflexible. Once you have created a TM object, it's
low level details cannot be changed. Strategy is more
flexible, but is harder to build and take a bit more CPU and
Memory.
An excellent summary of the trade-offs. Most of the time, if I
use a template pattern, it's because there are a lot of separate
customisation points, all, or almost all with default actions --
using a separate delegate object for each would be excessively
heavy, and using a single, unified delegate would basically mean
that the delegate is an instance of the template pattern. This
probably accounts for the extensive use of the template pattern
in GUI hierarchies.
As I mentionned elsewhere, there is also another subtle
distinction; the template pattern cannot be used for
customization which must take place in the constructor of the
base class. In C++, the dynamic call resolution will not go to
the derived class, and in languages where it does, you end up in
a class whose constructor hasn't been called yet. (The
practical difference is that in C++, your code aborts with a
"pure virtual function called" message, and in Java, it aborts
with an "uncaught NullPointerException" message. Except that
the AWT event handler loop catches the exception and ignores it,
so you end up with an action that didn't fully take place.)
I might add: in the context of C++, I prefer to speak of the
"template pattern" rather than a "template method"; "template
method" sounds too much like another name for "template
function", and of course, in C++, a template function has
nothing to do with the template pattern.
BTW: It's very good to see you back. Any plans for an update of
"Designing Object-Oriented C++ Applications Using the Booch
Method" to modern C++ and the UML?
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]