我一直在想,在Java中处理多个构造函数的最好(即最干净/最安全/最有效)的方法是什么?尤其是在一个或多个构造函数中没有指定所有字段时:
public class Book
{
private String title;
private String isbn;
public Book()
{
//nothing specified!
}
public Book(String title)
{
//only title!
}
...
}
如果没有指定字段,我该怎么办?到目前为止,我一直在类中使用默认值,这样字段永远不会为空,但这是一种“好”的做法吗?
发布于 2009-02-24 14:14:03
一个稍微简化的答案:
public class Book
{
private final String title;
public Book(String title)
{
this.title = title;
}
public Book()
{
this("Default Title");
}
...
}
发布于 2009-02-24 14:19:05
考虑使用Builder模式。它允许您在参数上设置默认值,并以清晰简洁的方式进行初始化。例如:
Book b = new Book.Builder("Catcher in the Rye").Isbn("12345")
.Weight("5 pounds").build();
编辑:它还消除了对具有不同签名的多个构造器的需要,并且可读性更好。
发布于 2009-02-24 14:36:18
您需要指定什么是类不变式,即对于类的实例始终为真的属性(例如,书的标题永远不会为空,或者狗的大小始终> 0)。
这些不变量应在构造过程中建立,并在对象的生命周期中保留,这意味着方法不应破坏这些不变量。构造函数可以通过强制参数或通过设置默认值来设置这些不变量:
class Book {
private String title; // not nullable
private String isbn; // nullable
// Here we provide a default value, but we could also skip the
// parameterless constructor entirely, to force users of the class to
// provide a title
public Book()
{
this("Untitled");
}
public Book(String title) throws IllegalArgumentException
{
if (title == null)
throw new IllegalArgumentException("Book title can't be null");
this.title = title;
// leave isbn without value
}
// Constructor with title and isbn
}
然而,这些不变量的选择在很大程度上取决于你正在编写的类,你将如何使用它,等等,所以你的问题没有明确的答案。
https://stackoverflow.com/questions/581873
复制相似问题