我遇到了以下困境:Java中没有多重继承,但我需要它,如何避免它?
以下是我开始考虑它的原因.
我需要一个具有几个特定属性和行为的文本框(处理焦点和模糊事件).我毫不犹豫地开发了DecorativeTextBox:
public class DecoratedTextBox extends TextBox implements FocusHandler, BlurHandler {
public void onBlur(BlurEvent event) {
//cool feature implementation
}
public void onFocus(FocusEvent event) {
//another cool feature
}
//other cool features
}
Run Code Online (Sandbox Code Playgroud)
我的GUI开始看起来很好,但我没有考虑PasswordTextBox.它还必须具有与DecoratedTextBox相同的属性和行为.但是PasswordTextBox本身就是TextBox,它实际上是另一个类层次结构分支.我立刻记得,如果TextArea还拥有所有那些很酷的属性和行为等,那将会很棒.
那么我的设计有什么问题导致对多重继承的想法呢?必须采取哪些措施来满足上述要求?
一些澄清
因此,我不得不继承PasswordTextBox,TextArea等以利用它们的功能(这些类来自GWT库).但我无法理解如何在这里编织构图.
更新
纠正我如果我理解安德斯约翰森以错误的方式说的话.
解决方案应如下所示:
public class DecoratedTextBox extend AbstractEventHandler {
private TextBox textBox;
//wrap TextBox methods
public String getText() {
return textBox.getText();
}
}
public class DecoratedPasswordTextBox extend AbstractEventHandler {
private PasswordTextBox passwordTextBox;
//wrap TextBox methods
//...
}
public class DecoratedTextArea extend AbstractEventHandler {
private TextAre textArea;
//wrap TextBox methods
//...
}
public abstract class AbstractEventHandler implements FocusHandler, BlurHandler {
public void onBlur(BlurEvent event) {
//default cool feature implementation
}
public void onFocus(FocusEvent event) {
//another default cool feature implementation
}
}
Run Code Online (Sandbox Code Playgroud)
更新
我尝试了Anders Johansen和Hilbrand Bouwkamp建议的变体,但在每种情况下我都遇到了一个问题,即我有一个方法(它的签名不能更改)添加小部件,其中一个args是Widget本身.因此,如果我不是从Widget的子类中继承子类,那么我会破坏很多类.
仍在继续思考解决方案.
我不知道你喜欢添加什么样的酷炫功能,但是制作一个TextBoxBaseDecorator类看起来像是这样的:
public class TextBoxBaseDecorater implements FocusHandler, BlurHandler, HasAttachHandlers {
private final TextBoxBase textBoxBase;
private final ArrayList<HandlerRegistration> handlers = new ArrayList<HandlerRegistration>();
/*
* Pass the TextBoxBase extending widget to be decorated.
*/
public TextBoxBaseDecorater(TextBoxBase textBoxBase) {
this.textBoxBase = textBoxBase;
textBoxBase.addAttachHandler(this);
}
public void onBlur(BlurEvent event) {
//cool feature implementation
}
public void onFocus(FocusEvent event) {
//another cool feature
}
public void onAttachOrDetach(AttachEvent event) {
if (event.isAttached() {
handlers.add(textBoxBase.addBlurHandler(this));
handlers.add(textBoxBase.addFocusHandler(this));
} else {
for (HandlerRegistration rh: handlers) {
rh.removeHandler();
}
handlers.clear();
}
}
//other cool features
Run Code Online (Sandbox Code Playgroud)
}
您可以创建为特定小部件创建包装的子类,如TextBox,PasswordTextBox和TextArea.
| 归档时间: |
|
| 查看次数: |
454 次 |
| 最近记录: |