我不会为此重写任何方法。如果你想创建的StackPane
提供此功能的一个子类,只需调用getChildren().addAll(...)
在构造函数中:
public class BackgroundEffectPane extends StackPane {
public BackgroundEffectPane(Node content) {
getChildren().addAll(createBackground(), freeze(...), content);
}
// code refactored from other answer...
}
当然,现在你不再真的需要在所有子类:
public class BackgroundEffectPane {
private final Node content ;
private final Parent effectPane ;
public BackgroundEffectPane(Node content) {
this.content = content ;
this.effectPane = new StackPane(createBackground(), freeze(...), content);
}
public Parent getEffectPane() {
return effectPane ;
}
// other code...
}
这通过不暴露窗格的底层实现和效果来更好地封装类(即,API不会公开您使用的是StackPane
)。
在这两种情况下,都没有任何东西阻止用户窗体干涉“BackgroundEffectPane”的内部工作,对吧?他们总是可以随意使用我从父类或构造函数返回的树。 –
在后一种情况下,它需要一个沮丧的(基本上是一个信仰的飞跃),因为'Parent'只暴露了一个不可修改的儿童名单,但是,一般来说这是真的。第二种方法在允许您更改实现而不破坏使用它的其他代码时更灵活(您并未承诺在该版本中始终使用“StackPane”)。 –
如果你真的想使用子类化方法,可以考虑继承'Region'并重写'layoutChildren()'和'计算Pref/Min/Max Width/Height'方法。 –