Visitor Pattern Explanation

前端 未结 2 1875
失恋的感觉
失恋的感觉 2020-12-01 03:01

So I\'ve read up all the documentation about the Visitor pattern, and I\'m still mightily confused. I\'ve taken this example from another SO question, could someone help me

2条回答
  •  温柔的废话
    2020-12-01 03:22

    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.

提交回复
热议问题