我在我的应用程序中使用 Retrofit,我有用于发出请求和解析响应的 POJO 类。目前我正在使用 JavaBeans 模式,并且对于所有 POJO 类的类中的所有变量都有 getter 和 setter。
例如,这是我的用户类
public class User {
@SerializedName("user_name")
private String userName;
@SerializedName("password")
private String userPassword;
@SerializedName("address_info")
private AddressInfo AddressInfo;
@SerializedName("contact_info")
private ContactInfo ContactInfo;
/*
*@return The userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName The userName
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return The userPassword
*/
public String getPassword() {
return userPassword;
}
/**
* @param userPassword The userPassword
*/
public void setPassword(String userPassword) {
this.userPassword = userPassword;
}
/// so on for the AddressInfo and ContactInfo
}
这很好用。我正在尝试使用构建器模式而不是 JavaBeans 模式。
我将我的用户类更改为:
public class User {
@SerializedName("user_name")
private String userName;
@SerializedName("password")
private String userPassword;
@SerializedName("address_info")
private AddressInfo AddressInfo;
@SerializedName("contact_info")
private ContactInfo ContactInfo;
public static class UserBuilder {
private String userName;
private String userPassword;
private AddressInfo AddressInfo;
private ContactInfo ContactInfo;
//builder methods for setting property
public UserBuilder userName(String user_name) {
this.userName = user_name;
return this;
}
public UserBuilder userPassword(String user_password) {
this.userPassword = user_password;
return this;
}
public UserBuilder AddressInfo(AddressInfo addressInfo) {
this.AddressInfo = addressInfo;
return this;
}
public UserBuilder ContactInfo(ContactInfo contactInfo) {
this.ContactInfo = contactInfo;
return this;
}
//return fully build object
public User build() {
return new User(this);
}
}
//private constructor to enforce object creation through builder
private User(UserBuilder builder) {
this.userName = builder.userName;
this.userPassword = builder.userPassword;
this.AddressInfo = builder.AddressInfo;
this.ContactInfo = builder.ContactInfo;
}
//Getters for userName,userPassword,AddressInfo and ContactInfo
}
地址信息类
public class AddressInfo {
@SerializedName("address_1")
private String address1;
@SerializedName("city")
private String city;
@SerializedName("state")
private String state;
@SerializedName("zip_code")
private String zipCode;
/**
* @return The address1
*/
public String getAddress1() {
return address1;
}
/**
* @return The city
*/
public String getCity() {
return city;
}
/**
* @return The state
*/
public String getState() {
return state;
}
/**
* @return The zip code
*/
public String getZipCode() {
return zipCode;
}
}
问题: 1. 我从 AddressInfo 和 ContactInfo POJO 类中删除了 setter。我是否也需要在 AddressInfo 和 ContactInfo 类中实现构建器模式?这就是模式的工作原理。
我怎样才能做到这一点:
User user = new User.UserBuilder().userName("test").userPassword("******").address("100 Townsend St").city("San Francisco").zip("94107").build();