问题描述
多年来,我尽可能避免 instanceof
。在适用的地方使用多态或访问者模式。我认为它在某些情况下只是简化了维护...是否还有其他一些应该注意的缺点?
Over the years, I've tried to avoid instanceof
whenever possible. Using polymorphism or the visitor pattern where applicable. I suppose it simply eases maintenance in some situations... Are there any other drawbacks that one should be aware of?
但是我确实在Java中看到它图书馆,所以我认为它有它的位置?在什么情况下更可取?这是不可避免的?
I do however see it here and there in the Java libraries so I suppose it has its place? Under what circumstances is it preferable? Is it ever unavoidable?
推荐答案
我可以想象一些情况,例如你有一些图书馆的对象,你可以' t扩展(或者这样做会不方便),也许与你的一些对象混合在一起,所有对象都在同一个集合中。
我想在这种情况下,使用instanceof来区分对这些对象进行一些处理可能很有用。
I can imagine some cases, for example you have some objects of a library, which you can't extend (or it would be inconvenient to do so), perhaps mixed with some objects of your, all with same base class, together in a collection.
I suppose that in such case, using instanceof to distinguish some processing on these objects might be useful.
在遗留代码的某些维护中同意你不能在很多旧类中注入一些新行为只是为了添加一个新的小特性或者一些错误修复......
Idem in some maintenance of legacy code where you cannot inject some new behavior in lot of old classes just to add a new little feature or some bug fix...
这篇关于是不是被认为是不好的做法?如果是这样,在什么情况下仍然更可取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!