这是我要采取的方法:
public interface MyInterface { MyInterface DEFAULT = new MyDefaultImplementation(); public static class MyDefaultImplemenation implements MyInterface { } }当然,MyDefaultImplementation可能需要是私有的,或者它自己的顶级类,这取决于合理的含义。
然后,您可以在实现中包含以下内容:
public class MyClass implements MyInterface { @Override public int someInterfaceMethod(String param) { return DEFAULT.someInterfaceMethod(param); } }与默认实现类(存在于其他地方但未被接口引用)相比,它具有更多的自记录性,并且最终更加灵活。使用此方法,您可以执行一些操作,例如仅在需要时将默认实现作为方法参数传递(您不能使用静态方法)。
当然,以上仅在不涉及状态的情况下有效。



