Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Automatically composite default methods of multiple interfaces

I have class implements multiple interfaces which have a same default default method. I am wondering how can I composite the default method from all the 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 the implementation the method is simply compositing process() from all interfaces. However I have to call IA.super.process(), IB.super.process(), IC.super.process() explicitly. If the interface list is long it's painfully to write all of them. Also I may have different classes to implement different combination of interfaces. Is there other syntax sugar/design pattern/library that allows me to do it automatically?

Update: compare with Composite pattern

Composite pattern is also considerable. But I want to use default method as mixin to give classes different behaviors, while composite pattern doesn't give me static type checking here. Composite pattern also introduces extra memory footprint.

like image 729
Yiqing Zhu Avatar asked Sep 20 '26 16:09

Yiqing Zhu


1 Answers

I think your mistake is defining multiple interfaces which are effectively identical (aside from differing default behaviour). It seems wrong in my mind and violates DRY.

I would structure this using the 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();
    }
}
like image 197
Michael Avatar answered Sep 22 '26 04:09

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!