Java访问者模式而不是instanceof开关 [英] Java visitor pattern instead of instanceof switch

查看:86
本文介绍了Java访问者模式而不是instanceof开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题中,据说我可以使用访客模式而不是一堆的instanceof 秒。 Jmg说:如果你不能自由改变A,B和C,你可以应用访客模式来实现同样的目标。

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."

据我所知,我仍需要制作A,B和C支持访问者(例如,有 accept()方法)。

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

我的问题是我绝对没有可能改变A,B和C.我只是从外国图书馆获得Car对象并且必须调用 wash()特定于卡车,赛车和公共汽车。

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.

我认为我还需要 if-else-if 构造的instanceof 秒。我是对的吗?

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

推荐答案

是的,要实现访客模式,您现在需要访问A,B和C的来源,除非所有类都具有相同的签名(因此所有类都具有相同名称的wash()方法)。如果是这种情况,您可以使用多态来调用正确的方法。

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.

否则,可以在源代码中向您无权访问的类添加功能水平。关于访客模式的维基百科文章(http://en.wikipedia.org/wiki/Visitor_pattern),Java示例下方有一个小脚注:

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:


注意:这种模式的一种更灵活的方法是创建一个包装器类,实现定义accept方法的接口。包装器包含一个指向CarElement的引用,可以通过构造函数初始化它。这种方法避免了必须在每个元素上实现接口。 [参见下面的文章Java技巧98文章]

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]

它引用了这篇文章: http://www.javaworld.com/javaworld/javatips/jw-javatip98.html

所以,总而言之,它是可能的,但它为你想做的小任务提供了大量的课程。如果我是你,我会坚持使用instanceof。

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.

这篇关于Java访问者模式而不是instanceof开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆