Visitor pattern - adding new ConcreteElement classes is hard?

前端 未结 4 817
孤街浪徒
孤街浪徒 2021-01-27 06:50

I read a book about the visitor pattern. It gives the same class diagram as in the oodesign\'s website.

It says that adding new ConcreteElement classes is hard. But I di

4条回答
  •  太阳男子
    2021-01-27 07:26

    If you add a new concrete element, then all of your visitor classes will need to add a new visit method for the new element. If you didn't use visitors, you would have to add the equivalent methods to your new concrete element anyway.

    But adding a new method to each your visitors may be harder than adding the equivalent set of methods to a new element class. The reason is that visitors often need to traverse the element tree structure and may need to manage its own state data as it does so. Adding a new visit method may require modifying that state data which involves thinking about how the new method interacts with existing visit methods for other elements.

    It may be simpler to add the equivalent methods to your new element class if you didn't have visitors because you will only need to worry about the internal state of the new concrete element which is more cohesive.

提交回复
热议问题