Java visitor pattern instead of instanceof switch

天涯浪子 提交于 2019-11-26 23:05:10

问题


In this question it is said I can use visitor pattern instead of a bunch of instanceofs. Jmg said "If you are not free to change A, B, and C, you could apply the visitor pattern to achieve the same."

As far as I understand I still have to make A, B and C support visitor (have an accept() method, for example).

My problem is I have absolutely no possibility to change A, B and C. I just get the Car object from the foreign library and have to call wash() method specific for trucks, race cars and buses.

I think I still need an if-else-ifconstruction with instanceofs. Am I right?


回答1:


Yes, to implement the visitor pattern now you need access to the source of A, B and C, unless all the classes have the same signature (so all have the wash() method with the same name). If that's the case, you can use polymorphism to call the correct method.

Otherwise, it is possible to add functionality to classes you don't have access to at source code level. On the Wikipedia article on the Visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) there is a small footnote below the Java example:

Note: A more flexible approach to this pattern is to create a wrapper class implementing the interface defining the accept method. The wrapper contains a reference pointing to the CarElement which could be initialized through the constructor. This approach avoids having to implement an interface on each element. [see article Java Tip 98 article below]

It references this article: http://www.javaworld.com/javaworld/javatips/jw-javatip98.html

So, all in all it's possible, but it gives an enormous number of classes for the small task you want to do. I'd stick with the instanceof's if I were you.



来源:https://stackoverflow.com/questions/8571490/java-visitor-pattern-instead-of-instanceof-switch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!