Visitor pattern - adding new ConcreteElement classes is hard?

前端 未结 4 857
孤街浪徒
孤街浪徒 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

    Well, you have to extend all your visitors.

    You have a caller, some elements that need to be visited, and an element - the visitor - that does the processing of the individual elements. Your goal is to keep the implementation of the elements and the caller fixed, and extend functionality via new visitors.

    Usually you have a lot of the concrete visitors. If you add a new type of element to be processed, you will need to change all the concrete visitors to take this into account.

    Why?

    well, imagine that the caller is "Factory", and you have the elements "Car" and "Bike".

    For operation "Paint" you have to have the methods

    void process(Car c); // Paint a car
    void process(Bike b); // Paint a bike
    

    Likewise for operations "Assemble", "Package", "Wash" etc.

    If you add an element "Scooter", all the operations have to be extended with a new method

    void process(Scooter s); // Handle a Scooter
    

    This is a bit of work. Also you may hit the isse where the element you add is so different from the others that you canøt easily fit them to the operations.

    Wikipedia (http://en.wikipedia.org/wiki/Visitor_pattern) says

    In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.

    That's a pretty abstract way of saying what I try to say above. Usually you'd add these methods to the elements, but if you can't you have to add the methods to somethign else, and pass that along to do the processing. This is a bit of extra work, but may be worth it, if the situation merits it.

提交回复
热议问题