Java级联继承:匿名类VS委派或内部类



我想知道我们是否可以在java中实现这样的功能。

我们有一个接口Interface1和一个适配器adapter,还有另一个从Interface1继承的接口,如下面的

public interface Interface1 {
void doSomething();
}
public interface Interface2 extends Interface1 {
void doOtherThing();
}
public abstract class Adapter implements Interface1 {
public void doSomething() {
System.out.println("Nope");
}
}

然后,我们想在依赖适配器的工厂方法中安装Interface2

public class SomeWhere {
public static Interface1 create1() {
return new Adapter () {};
}
public static Interface2 create2() {
return new Adapter & Interface2 () { //  Generic formalism, but obviously it does not compile
public void doOtherThing() {
System.out.println("Why me?!");
}
};
}
}

我的具体应用程序定义了像MyObject(getters+方法(和MyObject.Editable(setters(这样的接口,MyObject中的大多数代码都可以定义为接口中的默认代码(但我做了一个适配器!(,因为它依赖于getter方法,但我有几个实现,根据对象的性质,它们将有不同的getter,其他一些实现将需要Override,但它每次代表的代码不到5行。。。

因此,我正在寻找一种使用匿名类而不是代表团:

return new Interface2 () {
Interface1 delegate /* = new Adapter() */;

public void doSomething() {
delegate.doSomething();
}
public void doOtherThing() {
System.out.println("Why me?!");
}

}

(这里,有20多种方法,代码将无法保持可读性!(

或内部类别:

class AnotherAdapter extends Adapter implements Interface2 {...}

同样的问题是冗长,即使与代表团相比大幅减少。。。

我想我已经读过一些关于这方面的文章,但它是针对Java 8或更低版本的,也许一些技巧可以完成今天的工作(^_^('

PS:没有匿名类和内部(方法(类,我可以像这个一样实现它

public class SomeWhere {
public static void main(String[] args) {
create2().doOtherThing();
}
public static Interface2 create2() {
class Adapter2 extends Adapter implements Interface2 {
public void doOtherThing() {
System.out.println("Why me?!");
}
}
return new Adapter2();
}
}

但这只是另一种内心阶层。。。

为什么Adapter没有实现Interface2

public abstract class Adapter implements Interface1, Interface2 {
public void doSomething() {
System.out.println("Nope");
}
// ... omitted 500 methods that are placed here to save your day
}

然后你可以用退货

public class SomeWhere {
public static Interface2 create2() {
return new Adapter () {

// Only need to provide the implementation for that single abstract method here 
@Override
public void doOtherThing() {
System.out.println("Why me?!");
}
};
}
}

最新更新