Java visitor pattern instead of instanceof switch

≡放荡痞女 提交于 2019-11-27 21:31:46

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.

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