简体   繁体   English

不接触基数实现多态 class

[英]Achieve polymorphism without touching the base class

I have the following class hierarchy:我有以下 class 层次结构:

public abstract class Root {
    ...
}

public class A extends Root {
    ...
}

public class B extends Root {
    ...
}

public class C extends Root {
    ...
}

I want to apply a function func on objects of static-type Root , so that the behavior of the function will be dependent on the specific dynamic-type.我想在静态类型Root的对象上应用 function func ,这样 function 的行为将取决于特定的动态类型。

So obviously I can accomplish it using polymorphism.所以很明显我可以使用多态来完成它。 I could create an abstract function inside Root and implement it differently in every class that extends Root .我可以在Root中创建一个抽象 function 并在每个扩展Root的 class 中以不同的方式实现它。

However, what if the code of Root is inaccessible and I can't edit it?但是,如果Root的代码无法访问,无法编辑怎么办? The only solution I could think of is to implement func inside A , B and C separately, and then do something like this:我能想到的唯一解决方案是分别在ABC中实现func ,然后执行如下操作:

public static void applyFuncOnRootObject(Root object) {
    if (object instanceof A) {
        ((A) object).func()
    } else if (object instanceof B) {
        ...
    }
    ...
}

Is there a better solution that avoids the ugly casting and if-statements?有没有更好的解决方案来避免丑陋的转换和 if 语句?

You could create your own Root class.您可以创建自己的 Root class。

public class MyRoot extends Root{
     public void func(){}
}

And make classes A, B and C extends MyRoot instead of Root并使类 A、B 和 C 扩展 MyRoot 而不是 Root

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM