java - 构造函数重载 - Java 中的最佳实践
问题描述
构造函数也可以像任何其他方法一样重载,我知道这一事实。由于一项任务,我决定使用具有多个构造函数的抽象超类:
抽象超类:
protected ListSortierer()
{
this( null, null );
}
protected ListSortierer( List<E> li )
{
this( li, null );
}
protected ListSortierer( Comparator<E> comp )
{
this( null, comp );
}
protected ListSortierer( List<E> li, Comparator<E> com )
{
this.original = Optional.ofNullable( li );
this.comp = Optional.ofNullable( com );
}
要访问这些构造函数中的每一个,我还需要子类中的多个构造函数。
BubbleSort.java:
public ListBubbleSort()
{
super();
}
public ListBubbleSort( List<E> li )
{
super( li );
}
public ListBubbleSort( Comparator<E> com )
{
super( com );
}
public ListBubbleSort( List<E> li, Comparator<E> com )
{
super( li, com );
}
在这种情况下,子类的每个构造函数都会立即调用超类的构造函数。我想到我可以再次引用自己的构造函数并传递null
值:
public ListBubbleSort()
{
this( null, null );
}
public ListBubbleSort( List<E> li )
{
this( li, null );
}
public ListBubbleSort( Comparator<E> com )
{
this( null, com );
}
public ListBubbleSort( List<E> li, Comparator<E> com )
{
super( li, com );
}
这样做可以让我省略抽象超类中的 3 个重载构造函数,但会强制每个子类都遵循相同的模式。
我的问题是:在一致性的情况下,更好的方法是什么?处理抽象超类或子类中的缺失值?它对实例化有影响还是只是一个意见问题?
解决方案
在一致性的情况下,有什么更好的方法?
- 将所有子构造函数设为私有。
引入静态工厂方法。
ListBubbleSort.withList(List<E> list) ListBubbleSort.withComparator(Comparator<E> comparator)
调用适当的
super
构造函数。不要通过任何null
s。public static <E> ListBubbleSort withList(List<E> list) { return new ListBubbleSort(list); } private ListBubbleSort(List<E>) { super(list); } protected ListSortierer(List<E>) { // initialise only the list field this.origin = list; }
-
this.original = Optional.ofNullable(li);
如果您有 3 个以上的参数,请考虑构建器模式。
处理抽象超类或子类中的缺失值?
构造函数应该提供初始值。您没有传递初始值,您只是表示它们的缺席。
默认情况下,null
是引用类型的初始值。因此,如果尚未给出字段的值,则无需重新分配字段。
它对实例化有影响还是只是一个意见问题?
可读性、维护性。
我建议阅读Joshua Bloch 的 Effective Java:
创建和销毁对象
- 第 1 项:考虑静态工厂方法而不是构造函数
- 第 2 项:在面对许多构造函数参数时考虑使用构建器
推荐阅读
- scala - Scala sortBy缺少扩展函数的参数类型
- javascript - ACE 编辑器:如何将更改的数据移动到 $_POST 或 $_GET
- c - 是否要求指向两个不同本地空对象的指针比较不相等?
- google-cloud-ml - Google 的 mlengine 环境是否可以作为图像下载?
- styles - 如何启用 Sharepoint 2013 富文本编辑器功能区表格样式?
- android - 使用外键和房间的墓碑
- javascript - 监听 Web 组件上的全局事件
- rxjs6 - let 存在于 rxjs6 中吗?
- php - SQL 查询未插入
- amazon-web-services - 通过云形成控制 SNS 策略