简体   繁体   English

使用Java实现多个接口 - 有一种委托方式吗?

[英]Implementing multiple interfaces with Java - is there a way to delegate?

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. */

}

As said, there's no way. 如上所述,没有办法。 However, a bit decent IDE can autogenerate delegate methods. 但是,有点像IDE可以自动生成委托方法。 For example Eclipse can do. 例如Eclipse可以做到。 First setup a template: 首先设置一个模板:

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

then rightclick, choose Source > Generate Delegate Methods and tick the both if1 and if2 fields and click OK . 然后右键单击,选择Source> Generate Delegate Methods并勾选if1if2字段,然后单击OK

See also the following screens: 另请参见以下屏幕:

替代文字


替代文字


替代文字

There is one way to implement multiple interface. 有一种方法可以实现多个接口。

Just extend one interface from another or create interface that extends predefined interface Ex: 只需从另一个接口扩展一个接口或创建扩展预定义接口Ex的接口:

public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces 现在我们有扩展另一个接口的接口在out类中使用只需使用这个实现两个或更多接口的新接口

public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps 希望这可以帮助

Unfortunately: NO. 很不幸的是,不行。

We're all eagerly awaiting the Java support for extension methods 我们都急切地等待Java对扩展方法的支持

There's no pretty way. 没有好办法。 You might be able to use a proxy with the handler having the target methods and delegating everything else to them. 您可以使用具有目标方法的处理程序的代理,并将其他所有内容委托给它们。 Of course you'll have to use a factory because there'll be no constructor. 当然你必须使用工厂,因为没有构造函数。

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

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