Template Method vs Strategy (was: Exceptional C++ Item 23)
In article <pan.2006.05.16.09.07.06.406081@blueyonder.co.uk>,
seanf <clcppm-poster@this.is.invalid> wrote:
The item was originally gotw 15 back in the day, but the
archived discussion does not help me.
At question 3, this item advocates splitting the public nonvirtual
template method and the derivation interface into separate classes,
on the grounds that exposing a generic algorithm to clients and
using specialization from the derived class are two different
responsibilities.
I take the point about compilation dependencies, but otherwise I'm
finding that I prefer the original class better. Removed from the
template method class, the derivation class's members start to look
pretty unrelated.
When would you consider splitting a template method class like this
in the real world? Would there have to be special circumstances, or
is this an acceptable idiom to use generally?
<http://www.gotw.ca/gotw/015.htm>
This is more a design issue than a language issue, but it does bring up
some interesting questions (the kind of stuff that is discussed
regularly in comp.object if you care to mosey over. :-)
One obvious situation would be where Strategy can be used in more than
one Context. Having a separate interface would come in real handy in
that case. By using the Strategy pattern at the outset instead of
Template, we encourage such structural reuse.
Another is where we might want the Context to change strategies during
its lifetime. This simply cannot be done with a Template Method pattern.
Also, a Strategy pattern gives us more flexibility in general, for
example I can easily combine the Strategy pattern with the Decorator
pattern (where the Strategy interface is the same as the Decorator's
Component.) To do this with the AbstractClass in the Template Method
pattern can get quite harry because of the duplication of state.
Lastly, there is the Brittle Base Class problem. Every time you change a
base class you have to test not only the base class but every single
derived class. Obviously then, the less need for changing base classes
the better. If the base class has no behavior, then there is that much
less that might need changing...
Just to keep this at least a little C++ centric, I leave you with the
words of Mr. Stroustrup:
<http://www.artima.com/intv/modern.html>
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]