假设存在以下类:
public class Foo extends Spam{
public void bar(){};
//...many more useful functions...
}
我现在需要这个:
public class Fooish extends Foo{
public static boolean whichDelegate; //true for 1, false for 2
Foo delegate1;
Foo delegate2;
}
有没有办法自动让java委托(delegate)调用?
在查看了 SO 上的许多其他回复之后,我看到了三种可能的方法,但似乎都不适合我的特定用例:
Just override everything and do the switching logic yourself
问题是 Foo 是一个变化很大的类。这样做意味着每次 Foo 更改时,Fooish 也必须更改。
更糟糕的是,如果它没有改变并且函数eggs()被添加到Foo中,Fooish将调用eggs本身而不是它的委托(delegate)。困惑......
-
我很想能够做到这一点,但 Foo 是一个具体的类,将其功能提升到接口(interface)中似乎是不可能的。我不能碰垃圾邮件。
-
对性能有显着影响,但其他人很难理解。 Eclipse 可能无法找到对委托(delegate)的调用,这会损害可维护性。似乎是最好的选择,但对于应该有编译时解决方案的东西来说似乎很烦人。
我还找到了 this 但它是用 C# 编写的
最佳答案
如果我们控制 Foo
消费者代码,下面的模式是否合适?
public class FooDelegateSelector {
public static boolean selectDelegate1; //true for 1, false for 2
private Foo delegate1;
private Foo delegate2;
//delegates setup...
public Foo getSelectedDelegate() {
return selectDelegate1 ? delegate1 : delegate2;
}
}
Foo
使用代码:
final FooDelegateSelector fooSelector = new FooDelegateSelector(...);
final Foo selectedFoo = fooSelector.getSelectedDelegate();
selectedFoo.bar();
关于java - Java 中的条件委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39215666/