Java 8: automatically combined methods by default for multiple interfaces

I have a class that implements multiple interfaces that have the same default method. I am wondering how I can create a default method from all interfaces. For example:

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();
        ...
    }
}

      

In implementation, the method simply links process()

from all interfaces. However, I have to explicitly name IA.super.process()

, IB.super.process()

, IC.super.process()

. If the list of interfaces is long, it hurts to write all of them. Also I can have different classes to implement different combination of interfaces. Is there some other syntactic sugar / pattern / design library that allows me to do this automatically?

Update: Comparison with Composite Pattern

Composite drawing is also significant. But I want to use the default method as a mixin to give different behavior classes, while the composite template doesn't give me static type checking here. Composite drawing also adds extra memory space.

+3


source to share


1 answer


I believe your mistake is in defining multiple interfaces that are virtually identical (besides different default behaviors). This seems wrong in my mind and violates DRY .

I would structure this with a 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 //, IB, IC etc. 
{
    List<Processable> components = Arrays.asList(
         new A(), new B(), ...
    );

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

      

+7


source







All Articles