In this question it is said I can use visitor pattern instead of a bunch of instanceof
s. 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-if
construction with instanceof
s. Am I right?
Advertisement
Answer
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: https://www.infoworld.com/article/2077602/java-tip-98–reflect-on-the-visitor-design-pattern.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.