使用Java实现多个接口 - 有一种委托方式吗? [英] Implementing multiple interfaces with Java - is there a way to delegate?

查看:286
本文介绍了使用Java实现多个接口 - 有一种委托方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个实现多个接口的基类,例如下面的示例。

I need to create a base class that implements several interfaces with lots of methods, example below.

是否有更简单的方法来委派这些方法调用而不必创建大量重复方法?

Is there an easier way to delegate these method calls without having to create a horde of duplicate methods?

public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {

    private InterFaceOne if1;
    private InterFaceTwo if2;

    public MultipleInterfaces() {
      if1 = new ImplementingClassOne();
      if2 = new ImplementingClassTwo();
    }

    @Override
    public void classOneMethodOne { if1.methodOne(); }
    @Override
    public void classOneMethodTwo { if1.methodTwo(); }
    /** Etc. */


    @Override
    public void classTwoMethodOne { if2.methodOne(); }
    @Override
    public void classTwoMethodTwo { if2.methodTwo(); }
    /** Etc. */

}


推荐答案

如上所述,没有办法。但是,有点像IDE可以自动生成委托方法。例如Eclipse可以做到。首先设置一个模板:

As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:

public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
    private InterFaceOne if1;
    private InterFaceTwo if2;
}

然后右键单击,选择 Source> Generate Delegate Methods 并勾选 if1 if2 字段并单击确定

then rightclick, choose Source > Generate Delegate Methods and tick the both if1 and if2 fields and click OK.

另见以下屏幕:

这篇关于使用Java实现多个接口 - 有一种委托方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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