Java:扩展类的if-else实例 [英] Java: If-else instanceof extended classes

查看:71
本文介绍了Java:扩展类的if-else实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类X和一些扩展该类的类,将它们称为ABC.

I have an abstract class X and some classes who extend this class, call them A, B and C.

在其他一些类Y中,我有一些依赖于类类型的方法调用. if-else语句如下所示:

In some other class Y I have a few methodcalls that depend on the type of the class. The if-else statement looks like this:

public class Y implements InterfaceY {

    public Y(){
    }

    public String doStuff (X x, Boolean flag) {
    String s = "";
    if (x instanceof A) {
        doStuff((A) x));
    } else if (x instanceof B) {
        doStuff((B) x));
    } else if (x instanceof C) {
        doStuff((C) x, flag); 
    } else {
        throw new Exeption();
    }
    return s;

    private String doStuff(A a) {
        return "";
    }

    private String doStuff(B b) {
        return "";
    }

    private String doStuff(C c, Boolean flag) {
        return "";
    }
}

请注意,所有方法都具有相同的名称(doStuff()),但是根据类(有时是标记)的不同,该方法的实现也不同.当然,一旦从X扩展的分类增加,这看起来就很可怕,而且变得非常复杂.

Note that all methods have the same name (doStuff()) but depending on the class (and sometimes flag) call a different method implementation of that method. Of course this looks horrible and gets immensely complicated once the classed that are extended from X increase.

我是否可以通过某种方式创建一个中间接口(或其他接口)来处理大部分(或全部)if-else语句?

Is there any way that I can somehow create an intermediate Interface that (or something else) that takes care of the majority (or all) of the if-else statements?

推荐答案

首先将这些方法移出此处,并将它们分别放入A,B和C类中,以实现X接口.

First take these methods out of here, and put them in the A, B and C class respectively, implementing the X interface.

private String doStuff(A a) {
    return "";
}

private String doStuff(B b) {
    return "";
}

private String doStuff(C c, Boolean flag) {
    return "";
}

然后:

if (x instanceof A) {
    doStuff((A) x));
} else if (x instanceof B) {
    doStuff((B) x));
} else if (x instanceof C) {
    doStuff((C) x, flag); 

可以是x.doStuff();(您甚至不必传递A,B,C,因为这将在方法内部成为this.您将不得不弄乱的标志取决于您的具体情况.代码,例如,其他2个doStuff方法也可以接受该标志,但只是忽略它)

can just be x.doStuff(); (you don't even have to pass the A, B, C because that will be this inside the method. The flag you'll have to mess around with depending more specifically on your code. for example, the other 2 doStuff methods could accept the flag as well, but just ignore it)

这篇关于Java:扩展类的if-else实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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