Java 8:自动合成多个接口的默认方法
作者:互联网
我有类实现多个接口,它们具有相同的默认默认方法.我想知道如何从所有接口合成默认方法.例如:
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 //, IB, IC etc.
{
List<Processable> components = Arrays.asList(
new A(), new B(), ...
);
void process()
{
for(Processable p : components) p.process();
}
}
标签:default-method,java,java-8,design-patterns 来源: https://codeday.me/bug/20190727/1552437.html