J
James Kanze
[...]
There are generally three alternatives: templates with a traits
class (compile time decision), the template method pattern
(runtime decision at construction time, then fixed) and the
strategy pattern (allows changing the decision on an already
constructed object). In the case of C++, there is sometimes
another reason to prefer the strategy pattern: the concrete
strategy will generally be completely constructed before the
base class constructor of the main class starts; this allows
some degree of dynamic dispatch from the base class constructor.
Also, of course, templates with traits can be used to implement
the concrete derived classes of the template method or the
strategy patterns.
Actually, I thought of a better example. I see the strategy pattern
as a way to replace behavior dynamically. There is a static version
of the strategy pattern in C++ using templates, but as far as "design
patterns" goes I see this as primarily a runtime alteration.
There are generally three alternatives: templates with a traits
class (compile time decision), the template method pattern
(runtime decision at construction time, then fixed) and the
strategy pattern (allows changing the decision on an already
constructed object). In the case of C++, there is sometimes
another reason to prefer the strategy pattern: the concrete
strategy will generally be completely constructed before the
base class constructor of the main class starts; this allows
some degree of dynamic dispatch from the base class constructor.
Also, of course, templates with traits can be used to implement
the concrete derived classes of the template method or the
strategy patterns.