Java 8: default method for automatically synthesizing multiple interfaces
I have classes that implement multiple interfaces with the same default methods I want to know how to synthesize default methods 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 synthesizes process () from all interfaces But I have to explicitly call IA super. process(),IB.super. process(),IC. super. process(). If the interface list is long, it is painful to write all the interface lists In addition, I may have different classes to implement different interface combinations Are there other Syntax / design patterns / libraries that allow me to execute automatically?
Update: compare with composite mode
The composite pattern is also impressive But I want to use the default method as a mixin to provide different behavior for the class, while the composite pattern doesn't give me static type checking here Compound mode also introduces additional memory footprint
Solution
I think your mistake is to define multiple valid same interfaces (except different default behaviors) This seems to me wrong and violates dry
I will use composite pattern to build it:
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();
}
}
