C++: doubts about visitor pattern

前端 未结 5 1567
天命终不由人
天命终不由人 2021-02-08 21:23

I know what Visitor Pattern is and how to use it; this question is not a duplicate of this one.


I\'ve got a library where I put most of the reusable code I write,

5条回答
  •  暖寄归人
    2021-02-08 21:36

    First: "Visitor Pattern is a way to simulate Double Dispatching in C++." This is, erm, not fully right. Actually, double dispatch is one form of multiple dispatch, which is a way to simulate (the missing) multi-methods in C++.


    Whether operations on a class hierarchy should be implemented by adding virtual functions or by adding visitors is determined by the probabilities of adding classes vs. adding operations:

    • If the number of classes keeps changing more rapidly than the number of operations, use virtual functions. That is because adding a class requires modifying all visitors.
    • If the number of classes is relatively stable compared to the number of operations, use visitors. That is because adding a virtual function requires changing all classes in the hierarchy.

    Yes, many libraries do not come with a visitor interface.
    When we are just looking at the reasoning above, this would be right if the number of classes changes often. That is, if a library is released often, with new classes being added constantly, then providing a visitor interface wouldn't make much sense, because each time a new release brings new classes, everybody using the library need to adapt all of their visitors. So if we only looked at the above reasoning, a visitor interface would seem to only be helpful if the number of classes in a lib's class hierarchy seldom or never changes.

    However, with 3rd-party libraries there's another aspect to that: Usually, users cannot change the classes in the library. That is, if they need to add an operation, the only way they can do this is by adding a visitor - if the library provides the hooks for them to plug into it.
    So if you are writing a library and feel like users should be able to add operations to it, then you need to provide a way for them to plug their visitors into your lib.

提交回复
热议问题