Java 接口实现对 [英] Java Interface-Implementation Pair
问题描述
是否有为接口方法创建默认实现的首选方法或样式?假设我有一个常用的界面,在 90% 的情况下,我想要的功能是相同的.
Is there a preferred method or style of creating a default implementation for interface methods? Suppose I had a commonly used interface where in 90% of the cases the functionality I wanted was identical.
我的第一直觉是用静态方法创建一个具体的类.当我需要默认功能时,我会将功能委托给静态方法.
My first instinct is to create a concrete class with static methods. I would then delegate the functionality to the static methods when I want the default functionality.
这是一个简单的例子:
界面
public interface StuffDoer{
public abstract void doStuff();
}
方法的具体实现
public class ConcreteStuffDoer{
public static void doStuff(){
dosomestuff...
}
}
使用默认功能的具体实现
Concrete Implementation using default functionality
public class MyClass implements StuffDoer{
public void doStuff(){
ConcreteSuffDoer.doStuff();
}
}
这里有更好的方法吗?
编辑
在看到一些提议的解决方案后,我想我应该更清楚我的意图.本质上,我试图解决不允许多重继承的 Java.另外要明确的是,我并不是要声明 Java 是否应该允许多重继承.我只是在寻找为实现接口的类创建默认方法实现的最佳方法.
After seeing a few of the proposed solutions I think I should be more clear about my intent. Essentially I am trying to work around Java not allowing multiple inheritance. Also to be clear I am not trying to make a statement about whether or not Java should allow multiple inheritance. I am just looking for the best way to create a default method implementation for classes implementing an interface.
推荐答案
这是我会采取的方法:
public interface MyInterface {
MyInterface DEFAULT = new MyDefaultImplementation();
public static class MyDefaultImplemenation implements MyInterface {
}
}
当然,MyDefaultImplementation 可能需要是私有的,或者它自己的顶级类,这取决于什么是有意义的.
Of course, the MyDefaultImplementation may need to be private, or its own top level class, depending on what makes sense.
然后您可以在您的实现中包含以下内容:
You can then have the following in your implementations:
public class MyClass implements MyInterface {
@Override
public int someInterfaceMethod(String param) {
return DEFAULT.someInterfaceMethod(param);
}
}
与存在于其他地方但未被接口引用的默认实现类相比,它具有更多的自我记录性,并且最终更灵活.有了这个,你可以做一些事情,比如在需要时将默认实现作为方法参数传递(静态方法无法做到这一点).
Its a bit more self-documenting, and ultimately more flexible, than a default implementation class that exists elsewhere but is not referenced by the interface. With this you can do things like just pass the default implementation as a method parameter when required (which you cannot do with the static methods).
当然,以上仅在不涉及状态的情况下才有效.
Of course, the above only works if there is no state involved.
这篇关于Java 接口实现对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!