在这种情况下替代instanceof方法

在这种情况下替代instanceof方法

本文介绍了在这种情况下替代instanceof方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想知道更优雅的替代方案是什么:

Hello I'm wondering what would be some more elegant alternatives to something like this:

class Base...

class A extends Base...

class B extends Base...

//iterator of colection containing mixed As and Bs i want to remowe Bs and do omething with As
while(iterator.hasNext()) {
    Base next = iterator.next();
    if(next instanceof A) // do something
    if(next instanceof B)
        iterator.remove();
}

播种有哪些替代品...

Sow what are the alternatives...

感谢您的建议。

编辑:基类可能有许多子类而不只是两个,它们的数量可能会及时增长

edit: Base class may have many subclasses not just two and their numbers may grow in time

推荐答案

你真的需要从列表中删除它们吗?你为什么不只是在 Base 类中做某事(不做任何事情),然后只是将它覆盖到你想要的类 A

Do you really need to remove them from the list? Why don't you just have the method to do something in the Base class (doing nothing) and then just override it do to what you want on class A.

class Base{
    public void doSomething(){
    }
}


class A extends Base{
    @Override
    public void doSomething(){
        // do something
    }
}

然后你可以迭代列表并调用方法doSomething所有对象。

Then you could just iterate over the list and calling the method doSomething on all objects.

for(Base base : list) {
    base.doSomething();
}

这种方式只有覆盖了 doSomething的类()方法实际上会做一些事情。所有其他类只会在Base类中执行虚拟实现。

This way only the classes that have overridden the doSomething() method will actually do something. All the other classes will just execute the dummy implementation in the Base class.

如果 Base 是一个抽象类你可以将 doSomething()声明为抽象,并让扩展类实现它。使用这种方法,所有类都必须实现您不希望执行任何计算的方法和类,您只需提供该方法的虚拟实现。或者你甚至可以使用 doSomething()方法创建一个接口,并且(甚至可以做出更好的决定)并拥有 Base class实现它,因为只有扩展类才能实际实现该方法。

If Base was an abstract class you could declare the doSomething() as abstract and have the extending classes implement it. With this approach all classes would have to implement the method and classes for which you don't want any computation to be performed you would just provide a dummy implementation of that method. Alternatively you could even create an interface with the doSomething() method and have (which could even be a better decision) and have the Base class implement it, given that only the extending classes would actually implement the method.

这篇关于在这种情况下替代instanceof方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:14