在使用Java构建器模式构建的类中,默认构造函数有什么优势吗
我正在尝试使用Java创建一个不可变的对象。但我不知道默认构造函数在大型应用程序中是否有用。有人能在这方面指导我吗 这是我的班级:-在使用Java构建器模式构建的类中,默认构造函数有什么优势吗,java,jersey,immutability,builder-pattern,Java,Jersey,Immutability,Builder Pattern,我正在尝试使用Java创建一个不可变的对象。但我不知道默认构造函数在大型应用程序中是否有用。有人能在这方面指导我吗 这是我的班级:- package com.jersey.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xm
package com.jersey.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;
@XmlRootElement
@XmlType(name="todo")
@XmlAccessorType(XmlAccessType.FIELD)
@AutoProperty
public class Todo {
@XmlElement(name="summary")
private final String summary;
@XmlElement(name="description")
private final String description;
public String getSummary() {
return summary;
}
public String getDescription() {
return description;
}
private Todo(){
this(new Builder());
}
private Todo(Builder builder){
this.summary = builder.summary;
this.description = builder.description;
}
@Override
public boolean equals(Object o) {
return Pojomatic.equals(this, o);
}
@Override
public int hashCode() {
return Pojomatic.hashCode(this);
}
@Override
public String toString() {
return Pojomatic.toString(this);
}
public static class Builder{
private String description;
private String summary;
public Builder summary(String summary){
this.summary = summary;
return this;
}
public Builder description(String description){
this.description = description;
return this;
}
public Todo build(){
return new Todo(this);
}
}
}
默认构造函数也是如此:-
private Todo(){
this(new Builder());
}
序列化/反序列化中的帮助或其根本没有用处
我不知道它在大型应用程序中会产生什么影响,或者我不应该全部使用它。为什么要实现生成器?不可变对象不需要它。只需将类字段声明为final并在普通构造函数中分配它们。我正在尝试使用它,因为我未来的类将有许多字段,正如Joshua Bloch所提到的,如果类中有许多字段,我们应该使用生成器模式来创建对象。好的,出于这个原因,使用生成器模式是公平的。但是默认构造函数对于JAXB是必须的,所以我应该添加一个受保护的默认构造函数,它什么也不做