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屋!