Re: Policy-based class design or inheritance?
On Sep 29, 5:29 pm, Vincent <vdu...@gmail.com> wrote:
suppose we can choose between two approaches:
1) First approach (policy-based class design)
template <typename OutputPolicy>
class A {
...
public:
void print() {
OutputPolicy::print("...");
}
};
// Policy class
class OutputToStderr {
static void print(const std::string &msg) {
std::cerr << msg;
}
};
// other policy classes...
A<OutputToStderr> a;
...
a.print();
2) Second approach (classic inheritance)
class A {
...
public:
virtual void print() = 0;
}
class AToStderr : public A {
public:
void print() {
std::cerr << "...";
}
};
// other AToXXX classes
AToStderr a;
...
a.print();
Instinctively I tend toward the first approach. Inheritance is
undoubtedly a "pillar" of object-oriented programming, but if possible
I always look for an alternative design. (Inheritance introduces
issues not always obvious: it's really an "is a" model? the base class
should be made abstract? the polymorphic use of the class should be
allowed? the inheritance should be of interface or of implementation?
and so on.)
What alternative do you prefer?
Inheritance often can be too rigid because the association between
classes it forms can not be changed at runtime. Composition, on the
other hand, is much more flexible.
Here is an example of strategy design pattern (http://en.wikipedia.org/
wiki/Strategy_pattern) which is based on composition:
#include <stdio.h>
struct OutputStrategy
{
virtual void print(char const* msg) = 0;
};
class A
{
OutputStrategy* output_strategy_;
public:
A(OutputStrategy* output_strategy)
{
this->setOutputStrategy(output_strategy);
}
void setOutputStrategy(OutputStrategy* output_strategy)
{
output_strategy_ = output_strategy;
}
void print()
{
output_strategy_->print("...");
}
};
struct StdoutOutputStrategy : OutputStrategy
{
void print(char const* msg)
{
printf("%s\n", msg);
}
};
// other strategies
int main()
{
StdoutOutputStrategy sos;
A a(&sos);
a.print();
}
--
Max
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]