java - 在抽象类中初始化最终字段的最佳方法
问题描述
我想到了两种方法来初始化抽象类中的 final 字段,我必须选择最优雅、正确和其他开发人员可以理解的方法。我的抽象类将至少有 10 个实现。关于我应该选择哪一个的任何想法?
第一种方式:
public sealed abstract class GuiComponent permits DummyComponent {
private final Node internalNode;
//------Constructor
protected GuiComponent() {
internalNode = Objects.requireNonNull(initInternalNode());
}
//------Protected
protected abstract Node initInternalNode();
protected final Node getInternalNode() {
return internalNode; //subclasses will use this
}
}
public final class DummyComponent extends GuiComponent {
@Override
protected Node initInternalNode() {
HBox hbox = new HBox();
//some Node preparation
return hbox;
}
}
第二种方式:
public sealed abstract class GuiComponent permits DummyComponent {
private final Node internalNode;
//------Constructor
protected GuiComponent(Node internalNode) {
this.internalNode = Objects.requireNonNull(internalNode);
}
//------Protected
protected final Node getInternalNode() {
return internalNode; //subclasses will use this
}
}
public final class DummyComponent extends GuiComponent {
//------Constructor
public DummyComponent() {
super(initInternalNode());
}
//------Private
private static Node initInternalNode() {
HBox hBox = new HBox();
//...
return hBox;
}
}
解决方案
在我看来,第二种方法更好。原因是GuiComponent
构造函数请求 a Node
,因此更容易理解 aNode
实际上是需要的。这使它显式,而另一种方法使它隐式,因为除非您看到GuiComponent
代码,否则您无法知道该getInternalNode()
方法将在GuiComponent
构造函数中调用。你甚至可以说它是这个构造函数的副作用,因为我们都知道在软件开发中通常最好避免副作用。
推荐阅读
- typescript - 为什么具有可变参数计数的 TypeScript 函数不接受数组?
- timsort - 当合并在 Timsort 中运行 A,B 时(在函数 merge_lo 中),它说“必须在合并结束时也有 ssa.keys[na-1] 属于”。为什么?
- c# - XPath 表达式在不应该返回节点时返回
- awk - 如何使用 awk 限制日志
- azure-aks - azds.yaml 中是否有配置选项来增加 azds up 期间的超时?
- c - 计算不同函数中保留的内存的函数
- html - 如何制作一个带有删除和链接的按钮?
- python - 点之间的矢量化/线性代数距离?
- php - 使用 PHP 中的 API 通过网站获取 Twitter 个人资料
- java - 通过转换为具体(无界通配符)类型产生的意外未经检查的转换警告