加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java 8:自动合成多个接口的默认方法

发布时间:2020-12-15 04:38:11 所属栏目:Java 来源:网络整理
导读:我有类实现多个接口,它们具有相同的默认默认方法.我想知道如何从所有接口合成默认方法.例如: interface IA { default void doA() {} default void process() { // do something }}interface IB { default void doB() {} default void process() { // do som
我有类实现多个接口,它们具有相同的默认默认方法.我想知道如何从所有接口合成默认方法.例如:

interface IA {
    default void doA() {} 
    default void process() { 
        // do something 
    }
}

interface IB { 
    default void doB() {}
    default void process() { 
        // do something 
    }
}

interface IC {
    default void doC() {} 
    default void process() { 
        // do something 
    }
}

// other similar interfaces
....    

class MyClass implements IA,IB,IC,... {
    public void process() {
       // question: how to avoid iterate all the interfaces? 
       IA.super.process();       
       IB.super.process();
       IC.super.process();
       ...
    }
}

class AnotherClass implements IA,ID,IF,IH,... {
    public void process() {
        IA.super.process();
        ID.super.process();
        IF.super.process();
        IH.super.process();
        ...
    }
}

在实现中,该方法只是从所有接口合成process().但是我必须显式地调用IA.super.process(),IB.super.process(),IC.super.process().如果接口列表很长,那么编写所有接口列表是很痛苦的.此外,我可能有不同的类来实现不同的接口组合.是否有其他语法糖/设计模式/库允许我自动执行?

更新:与复合模式进行比较

复合图案也很可观.但是我想使用默认方法作为mixin来为类提供不同的行为,而复合模式在这里不给我静态类型检查.复合模式还引入了额外的内存占用.

解决方法

我认为你的错误是定义了多个有效相同的接口(除了不同的默认行为).这在我看来似乎是错误的并且违反了 DRY.

我会使用composite pattern来构建它:

interface Processable
{
    void process();
}
public interface IA extends Processable //and IB,IC etc.
{
    default void doA()
    {
        // Do some stuff
    }
}


final class A implements IA
{
    void process() { /* whatever */ }
}


class Composite implements IA //,IC etc. 
{
    List<Processable> components = Arrays.asList(
         new A(),new B(),...
    );

    void process()
    {
         for(Processable p : components) p.process();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读