How to avoid downcast?
The typical visitor pattern performs no downcast, thanks to a double-dispatch strategy:
// Visitor.hpp
class EventBar;
class EventFoo;
class Visitor {
public:
virtual void handle(EventBar const&) = 0;
virtual void handle(EventFoo const&) = 0;
};
// Event.hpp
class Visitor;
class Event {
public:
virtual void accept(Visitor&) const = 0;
};
And the implementations:
// EventBar.hpp
#include <Event.hpp>
class EventBar: public Event {
public:
virtual void accept(Visitor& v);
};
// EventBar.cpp
#include <EventBar.hpp>
#include <Visitor.hpp>
void EventBar::accept(Visitor& v) {
v.handle(*this);
}
The key point here is that in v.handle(*this)
the static type of *this
is EventBar const&
, which selects the correct virtual void handle(EventBar const&) = 0
overload in Visitor
.
The idea of events is to pass detailed objects through generalized (and agnostic) interface. Downcast is inevitable and part of the design. Bad or good, it's disputable.
Visitor pattern only hides the casting away from you. It's still performed behind the scenes, types resolved via virtual method address.
Because your Event
already has the id, it's not completely agnostic of the type, so casting is perfectly safe. Here you're watching the type personally, in visitor pattern you're making compiler take care of that.
"Whatever goes up must go down".