对所有实现都没有意义的接口方法 类
interface method that does not make sense for all implementing classes
所以我在这个使用 Spring 并在各处注入接口的好项目中工作。问题是:在我的一个实现者中,我有这个方法在那个特定的实现中才有意义。我应该如何在其他 classes 中实现此方法?
例如:
public interface A {
public String methodThatMakesSenseOnlyToImplementationA();
}
现在实施 classes:
public class ImplementingInterfaceA implements A {
public String methodThatMakesSenseOnlyToImplementationA() {
//many many crazy things here
}
}
为此class,我必须实现该方法,但返回空字符串看起来很脏。
public class Nothing implements A {
public String methodThatMakesSenseOnlyToImplementationA() {
// this implementation will never use the method methodThatMakesSenseOnlyToImplementationA
}
}
如何很好地解决这个问题?
而不是为 class Nothing
实现接口 A。扩展 class ImplementingInterfaceA
。它将继承已经实现的方法。
或者,如果您使用的是 java8,请在您的界面中使用默认方法。
当没有合理的实现并且您知道该方法未被调用时,抛出 UnsupportedOperationException
。
您可以将额外方法移动到另一个 interface
- 比如说 B
- 这样您将有两个接口 A
和 B
.
方法一
public interface B {
//here are the methods that make some sense for all the classes
}
接口可以扩展接口:
public interface A extends B {
public String methodThatMakesSenseOnlyToImplementationA();
}
类可能实现不同的接口:
public class ImplementingInterfaceA implements A {
. . .
}
public class Nothing implements B {
. . .
}
方法二
你可以有完全分离的接口:
public interface B {
//here are the methods that make some sense for all the classes
}
public interface A {
public String methodThatMakesSenseOnlyToImplementationA();
}
允许类实现一个或多个接口:
public class ImplementingInterfaceA implements A, B {
. . .
}
public class Nothing implements B {
. . .
}
所以我在这个使用 Spring 并在各处注入接口的好项目中工作。问题是:在我的一个实现者中,我有这个方法在那个特定的实现中才有意义。我应该如何在其他 classes 中实现此方法? 例如:
public interface A {
public String methodThatMakesSenseOnlyToImplementationA();
}
现在实施 classes:
public class ImplementingInterfaceA implements A {
public String methodThatMakesSenseOnlyToImplementationA() {
//many many crazy things here
}
}
为此class,我必须实现该方法,但返回空字符串看起来很脏。
public class Nothing implements A {
public String methodThatMakesSenseOnlyToImplementationA() {
// this implementation will never use the method methodThatMakesSenseOnlyToImplementationA
}
}
如何很好地解决这个问题?
而不是为 class Nothing
实现接口 A。扩展 class ImplementingInterfaceA
。它将继承已经实现的方法。
或者,如果您使用的是 java8,请在您的界面中使用默认方法。
当没有合理的实现并且您知道该方法未被调用时,抛出 UnsupportedOperationException
。
您可以将额外方法移动到另一个 interface
- 比如说 B
- 这样您将有两个接口 A
和 B
.
方法一
public interface B { //here are the methods that make some sense for all the classes }
接口可以扩展接口:
public interface A extends B { public String methodThatMakesSenseOnlyToImplementationA(); }
类可能实现不同的接口:
public class ImplementingInterfaceA implements A { . . . } public class Nothing implements B { . . . }
方法二
你可以有完全分离的接口:
public interface B { //here are the methods that make some sense for all the classes } public interface A { public String methodThatMakesSenseOnlyToImplementationA(); }
允许类实现一个或多个接口:
public class ImplementingInterfaceA implements A, B { . . . } public class Nothing implements B { . . . }