java抽象类,其覆盖方法添加特定组件
实现一些扩展抽象超类的类的最佳方法是什么,其中每个类总是添加一个组件,但组件可能不同
我定义了一个抽象类,它实现了拖放行为,并有一个组件来显示和编辑一些字段。具体组件不同,在某些情况下,字段可能为空,可能有多个字段,以此类推。 在抽象类中,我通过抽象getComponent()方法添加组件。子类提供自己的实现。 子类使用在构造函数中传递的不同字段或根据构造函数中提供的参数计算的不同字段
这些字段在超级构造函数调用中还不可用,因此无法在抽象类的构造时调用getComponent()方法。 解决方法是在onInitialize()中添加组件,或者让实现类来添加组件(是否?)但也许整个方法是反模式的
代码段:
public abstract class AbstractContainer extends Panel {
AbstractContainer( String markupId, IModel<> somemodels ..)
{
super( markupId );
this.setOutputMarkupId( true );
this.add( new DragDropBehavior( "result" ) {
//some stuff
});
// cannot do this.add(getComponent()) here
// implementations use fields that have not been set
// yet in child classes
}
abstract protected Component getComponent();
}
public class MyPanel extends AbstractContainer {
IModel mySpecificFieldModel;
MyPanel( String markupId, IModel<> somemodels, IModel mySpecificFieldModel)
{
super( somemodels );
this.mySpecificFieldModel=mySpecificFieldModel;
}
protected Component getComponent()
{
Component component = new MyComponent("id", this.mySpecificFieldModel);
return component;
}
}
# 1 楼答案
让
onInitialize()
调用可重写的工厂方法是Wicket中的常见模式:# 2 楼答案
也许Composite模式可以帮助您