Java 在类自己的接口中初始化类
我看了一些代码,注意到这样的结构:Java 在类自己的接口中初始化类,java,design-patterns,Java,Design Patterns,我看了一些代码,注意到这样的结构: public interface TestIntrerface { void doFirst(); void doSecond(); } public interface Interface1 extends TestIntrerface { Interface1 inter = new FirstClass(); } public interface Interface2 extends TestIntrerface { Interfac
public interface TestIntrerface {
void doFirst();
void doSecond();
}
public interface Interface1 extends TestIntrerface {
Interface1 inter = new FirstClass();
}
public interface Interface2 extends TestIntrerface {
Interface2 intr = new SecondClass();
}
public class FirstClass implements Interface1 {
public void doFirst() {
//...
}
public void doSecond() {
//...
}
}
public class SecondClass implements Interface2 {
public void doFirst() {
//...
}
public void doSecond() {
//...
}
}
public class Test {
public static void main(String[] args) {
Interface1.inter.doFirst();
Interface2.intr.doSecond();
}
}
它对我来说很有潜力,但我以前从未见过这种结构。
两个问题:inter
和intr
的示例。这不是一种模式,我也不会说这是一种好的做法
Interface1
和Interface2
毫无意义:它们不补充/实现它们扩展的接口。基本上,它们是可以在其他地方定义的常量的持有者。请注意,常量绑定到特定类,而接口具有更广泛的含义,即提供通用接口inter
和intr
非常糟糕,它们不能说明这些常量代表/做什么interface TestInterface {
void doFirst();
void doSecond();
TestInterface EMPTY = new TestInterface() {
@Override
public void doFirst() {}
@Override
public void doSecond() {}
};
}
其中
EMPTY
表示它是接口的默认(且为空)实现。请注意,我将其命名为EMPTY
(而不是EMPTY
),因为它始终是一个公共静态final
字段。您必须阅读一些有关接口的内容。你们调用的模式只是简单的变量声明,若你们读了,你们就会知道,接口中的变量是初始化的,因为默认情况下它们是公共静态final,你们用引用创建的对象和创建公共静态final int=1是一样的;