将未实现的方法委托给Java中包含的对象的最短方法是什么? [等候接听]
|
我在“辅助对象”中包含“主要对象”(具有大多数功能),这将提供方便的方法.我只有一个接口可用,除了返回的对象与工厂方法的接口.我在想一个“扩展”这个对象的好方法是组合,但是我的超类必须实现主对象接口的问题,这将是大约600行的存根代码. 显然,一个简单但冗长的解决方案是填写所有存根,以便它们只调用主对象的方法.在Java中有比这更好的方法吗?在我熟悉的其他语言中,有一些方法可以为辅助对象中未实现的方法执行自动委派. 例:
class Helper implements Interface {
Primary primary;
Helper(Primary _primary) {
primary = _primary;
}
void helper() {
doStuff();
}
// 500 lines of this
void stub() {
primary.stub();
}
}
注意: 最初的计划是使用正则表达式将Eclipse中的所有存根TODO替换为实际调用.将寻找一个自动执行此操作的Eclipse工具.此外,看起来扩展接口或使用代理最终更好,所以将追求. 解决方法有一些可能性.第一:使用委托调用的抽象实现. abstract class InterfaceDelegator implements Interface {
protected final Interface primary;
public InterfaceDelegator() {
this.primary = primary;
}
// implements all the calls as: primary.call(...)
}
class Helper extends InterfaceDelegator {
// override just the methods you need
}
第二:使用代理(可能更干净). 见:http://docs.oracle.com/javase/1.5.0/docs/guide/reflection/proxy.html final Interface primary = ...;
return (Interface) Proxy.newProxyInstance(Inteface.class.getClassLoader(),new Class[] { Interface.class },new InvocationHandler() {
public Object invoke(Object proxy,Method m,Object[] args) throws Throwable {
// if m is a method that you want to change the behaviour of,return something
// by default,delegate to the primary
return m.invoke(primary,args);
}
});
调用处理程序将通过执行您已编码的方法来处理调用,而其他所有方法都将委派给主实现. 第三:使用IDE生成方法(正如其他人指出的那样). (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
