我真的不想问这个问题。也许是因为有些愚蠢,但冗长让我有动力这样做……所以我希望你对我充满热情……谢谢。
我有一个带有一堆方法的简单界面。
public interface MyInterface
{
public Integer getSolution();
public void setSolution(final Integer a);
public void markAsSent(final boolean sent);
public boolean wasSent();
......
......
}
我们正在扩展 ZK 组件
,例如 Textbox,Datebox,Bandbox,Decimalbox
我们有类似的东西
public class CustomTextBox extends Textbox implements MyInterface
{}//we add the implementations of the methods...
当我需要扩展另一个 ZK 组件 Datebox、Bandbox、Decimalbox 等时,问题就出现了。
MyInterface
的方法实现对于 ALL 是相同的。
只像这样改变类的扩展......
public class CustomBandBox extends Bandbox implements MyInterface
public class CustomComboBox extends Combobox implements MyInterface
public class CustomDecimalBox extends Decimalbox implements MyInterface
因为我非常讨厌冗长,所以我想创建一个类来实现 MyInterface
并扩展 Zk Components
因为 Java 不允许多重继承 如何我可以做这样的事情吗..
任何变通方法,如使用 Generics
或任何帮助,我们都非常感激......
我们正在使用 Java 7
我认为这可以在 Java 8
中使用 defaults methods
解决,但我仍然坚持使用 7
最佳答案
在那种情况下你应该使用合成。引用策略设计模式,也许来 self 最喜欢的 DP 书 Head First Design Patterns 之一。在第一章中描述了一个设计原则,你应该经常考虑组合,而不是过度使用继承。
在 MyInterface 中声明的行为应该在 onw 类中实现并通过组合实现:
public class MyImplementation implements MyInterface {
// perhaps you need a reference to the ZK Component here
private Component comp;
public MyImplementation(Component comp){
this.comp = comp;
}
}
public class CustomBandBox extends Bandbox implements MyInterface {
private MyImplementation impl = new MyImplementation(this);
public Integer getSolution(){
return impl.getSolution();
}
}
关于Java multiple extends Zk Component 变得非常冗长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110310/