Visitor pattern is used to implement double dispatch. In plain words it means that the code that gets executed depends on runtime types of two objects.
When you call a regular virtual function, it is a single dispatch: the piece of code that gets executed depends on the runtime type of a single object, namely, the one the virtual method of which you are calling.
With the visitor pattern, the method that is being called ultimately depends on the type of two objects - the type of the object implementing the equipmentVisitor
, and the type of the object on which you call accept
(i.e. the equipmentVisited
subclass).
There are other ways to implement double dispatch in C++. Item 31 of Scott Meyer's "More Effective C++" treats this subject in depth.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…